Sunday, August 10, 2008

Perl - return value of a function

Can you guess the output of the following Perl code?

$sum = add(3, 5);
print $sum."\n";

sub add
{
$a = shift;
$b = shift;

return ($a + $b);
}

Yes, it prints 8.

Now what about the following code?

$sum = add(3, 5);
print $sum."\n";

sub add
{
$a = shift;
$b = shift;
}

hmm... what should it print? It prints 5 ! A garbage value?
Not actually. I have found that in Perl if you don't return anything, it returns the value of the last variable in the function.

Now you can tell the output of the following code :-)

$sum = add(3, 5);
print $sum."\n";

sub add
{
$a = shift;
$b = shift;

$c = 10;
}

yes, it's 10 !

1 comment:

Ruud said...

Actually the return value of a funtion is not that of the last variable. The return value of a function is the result of the last expression in the function.

$b = shift is an expression that has as result the value of the right hand side.

So, you can do things as

sub foo {
shift;
}

print foo (2, 3, 4);

or even

sub foo {
5;
}

with regards,
Ruud