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
To return a value from a subroutine, block, or do function in Perl, we use the return() function. The Value may be a scalar, a list, or a hash value. Its context is selected at runtime.
return() function in Perl returns Value at the end of a subroutine, block, or do function. Returned value might be scalar, array, or a hash according to the selected context.
For this, you use -> and either [] to tell Perl you want to access a list element, or {} to tell Perl you want to access a hash element: $scalar = $ref->[ 1 ]; $scalar = $ref->{ name1 }; NOTICE: you're accessing one element, so you use the $ sign.
Passing Arguments to a Subroutine You can pass various arguments to a subroutine like you do in any other programming language and they can be acessed inside the function using the special array @_. Thus the first argument to the function is in $_[0], the second is in $_[1], and so on.
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.
See Scalar vs List Assignment Operator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With