Perl 101 routine and return value

I do not understand how this will return 4 as an answer. Not sure what is going on inside the routine.

sub bar {@a = qw (10 7 6 8);} my $a = bar(); print $a; # outputs 4 
+4
source share
3 answers

A subroutine is invoked in a scalar context. The last statement in the routine is the @a assignment, which is an expression and therefore becomes the implied return value. In a scalar context, this is estimated by the number of elements returned by the right-right side of the assignment (which happens the same as the number of elements in @a ).

+12
source

Each of the subroutine return expressions (i.e., the Operand of the return and any final subroutine expressions) is 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 returned expression is the destination of the list. ( @a and qw are assignment operands and are thus evaluated before assignment.) List assignment in a scalar context is evaluated by the number of elements for which its right-hand side is calculated.

See Scalar vs. List Assignment Operator

+5
source

In Perl, the return value of a subroutine is the last expression if there is no return .

From perlsub docs:

If no return is found, and if the last expression is an expression, its value is returned. If the last statement is a loop control structure like foreach or some time, the return value is not specified. empty sub returns an empty list.

+3
source

Source: https://habr.com/ru/post/1496650/


All Articles