Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl 101 subroutine and return value

Tags:

perl

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

like image 475
airnet Avatar asked Aug 12 '13 18:08

airnet


People also ask

How do I return a value in Perl?

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.

How do I return an array from a subroutine in Perl?

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.

How do I return a subroutine hash in Perl?

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.

How do you pass a variable in Perl subroutine?

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.


2 Answers

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).

like image 92
Ted Hopp Avatar answered Sep 30 '22 17:09

Ted Hopp


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

like image 22
ikegami Avatar answered Sep 30 '22 16:09

ikegami