I don't understand how this would return 4 as an answer. Not sure what is happening inside the subroutine.
sub bar {@a = qw (10 7 6 8);}
my $a = bar();
print $a;
# outputs 4
I don't understand how this would return 4 as an answer. Not sure what is happening inside the subroutine.
sub bar {@a = qw (10 7 6 8);}
my $a = bar();
print $a;
# outputs 4
The subroutine is called in a scalar context. The last statement in the subroutine is the assignment to @a
, which is an expression and so becomes the implied return value. In a scalar context, this evaluates to the number of elements returned by the assignment's right-hand side (which happens to be the same as the number of elements in @a
).
Each of a subroutine's return expressions (i.e. the operand of return
statements and any final expressions of a sub) are evaluated in the same context as the subroutine call itself.
sub f {
...
return THIS if ...;
return THIS if ...;
...
if (...) {
...
THIS
} else {
...
THIS
}
}
In this case, the return expression is a list assignment. (@a
and qw
are operands of the assignment and are thus evaluated before the assignment.) A list assignment in scalar context evaluates to the number of elements to which its right-hand side evaluated.
In Perl, the return value of a subroutine is the last expression evaluated if there is no return
statement specified.
From the perlsub docs:
If no return is found and if the last statement is an expression, its value is returned. If the last statement is a loop control structure like a foreach or a while , the returned value is unspecified. The empty sub returns the empty list.