Search code examples
perlperl-data-structures

Why does function call as argument to the push cause 'Not an ARRAY reference' in Perl?


Would somebody be so pleasant to explain why does the next thing happen? Here is the code:

#!/usr/bin/perl
use v5.14;
use warnings;

my @arr = (1, 2, 3);

sub func
{
    return @arr;
}

push(&func(), 4);

say @arr;

When I try to run it, the output is Not an ARRAY reference at ....

I suppose that this is because &func() evaluates not to the @arr, but to a plain list 1, 2, 3 and 1 is treated as ARRAY argument to the push. Can somebody explain why does this happen, cause in the push documentation I found nothing related to this.

Thanks in advance.


Solution

  • It's impossible for a sub to return an array. You are returning the result of evaluating the array in list context, which is to say you are returning a list of its content. Obviously, that's not what you want.

    push will now accept a reference to an array, so you could use

    sub func {
       return \@arr;
    }
    
    push(func(), 4);
    

    Note that push required an array literal until recently, so must use the following if you want backwards compatibility:

    sub func {
       return \@arr;
    }
    
    push(@{ func() }, 4);
    

    PS — Note that I removed the &. Why are you telling Perl to ignore the prototype of a sub that has no prototype?