zhenyisong has asked for the wisdom of the Perl Monks concerning the following question:

use Modern::Perl; use autodie; sub find_chores { return (8,456,310); } my $value = find_chores(); say $value;
I think the return value is the list contains 3 numbers, and when in the scalar context, the $value should be 3. However, the return value is the last element of the list. Even I used the conserved word 'scalar' before the function find_chores(), the returned value was still 310, not 3 as the expected. This is confusing me. Do I miss something here?

Replies are listed 'Best First'.
Re: why the output is not my expected?
by choroba (Cardinal) on Mar 31, 2017 at 07:13 UTC
    List is not array. Read about the Comma Operator in the documentation.

    In scalar context it evaluates its left argument, throws that value away, then evaluates its right argument and returns that value.

    To get your expected output, you have to create an array:

    sub find_chores { return my @arr = (8, 456, 310); }

    or, if you don't want to name it:

    sub find_chores { return @{ [ 8, 456, 310 ] } }

    Update: there are more than two ways how to create an array:

    sub find_chores { return map $_, 8, 456, 310; }

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
      Thanks,@choroba. I did not notice the difference between array and list.
Re: why the output is not my expected? (updated)
by haukex (Archbishop) on Mar 31, 2017 at 07:14 UTC

    find_chores() is called in scalar context. That scalar context is passed through to the return statement, which places (8,456,310) into scalar context. The Comma Operator in scalar context "evaluates its left argument, throws that value away, then evaluates its right argument and returns that value", in this case 310.

    Update: choroba beat me to it ;-)

    Update 2: If you want to control the return values of your functions in void, scalar, and list context more precisely than choroba showed, see wantarray:

    sub somefunc { my $arg = shift; print "doing something with $arg\n"; return unless defined wantarray; print "doing expensive return value calc\n"; return wantarray ? ('foo','bar') : 'quz'; } somefunc("a"); # just prints "doing something with a" my $x = somefunc("b"); print "$x\n"; # prints "quz" my @y = somefunc("c"); print join(",",@y),"\n"; # prints "foo,bar"