Reputation: 1743
I like perl the more I am getting into it but I had a question about a line I saw in a subroutine in a module I am looking through.
my $var = 1;
....
....
....
....
$var;
What throws me is just seeing that $var
all by itself on a line. Is that just a roundabout way of returning 1
?
Many thanks!
Jane
Upvotes: 3
Views: 204
Reputation: 93770
In perl the value of a block is the value of the last expression in the block. That is just a shorthand for return $var
.
EDIT: Purists point out that that blocks in general do not return values (like they do in Scala, for example) so you can't write:
my $x = if (cond) { 7 } else { 8 }; # wrong!
The implicit return value of a subroutine, eval or do FILE is the last expression evaluated. That last expression can be inside a block, though:
sub f {
my $cond = shift;
if ($cond) { 7 } else { 8 } # successfully returns 7 or 8 from f()
}
There is the superficial appearance of the if/else blocks returning a value, even though, strictly speaking, they don't.
Upvotes: 6
Reputation: 74252
Quoting the last line of perldoc -f return
:
In the absence of an explicit
return
, a subroutine, eval, or do FILE automatically returns the value of the last expression evaluated.
Upvotes: 6