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

This code:
@perls = (1, 2, 3, 4) sub foo { my @foo = @{shift()}; return join $/, @foo } print foo(\@perls)
Produces the following output:
one two three four
however, if i change line 4 to:
my @foo = @{shift};
no output is produced after running. How exactly is @{shift()} being passed the contents of @_? At the moment this looks like witchcraft to me but I'd really like to know how this works.
Thanks,

Replies are listed 'Best First'.
Re: Can someone clarify what's happening here
by toolic (Bishop) on Aug 11, 2010 at 01:41 UTC
      use strict causes it to whinge that i'm not using my to declare @perls, but if that's fixed, the code still exhibits the same behavior (@{shift()} works, @{shift} does not)
        Did you forgot to remove the parens? You should have gotten a warning and a strict error, but of which explain the issue.
        use strict; use warnings; my @perls = (1, 2, 3, 4); sub foo { my @foo = @{shift}; return join $/, @foo } print foo(\@perls)
        Ambiguous use of @{shift} resolved to @shift at a.pl line 7. Global symbol "@shift" requires explicit package name at a.pl line 7. Execution of a.pl aborted due to compilation errors.
Re: Can someone clarify what's happening here
by derby (Abbot) on Aug 11, 2010 at 10:21 UTC

    Sometimes, the use of B::Deparse is helpful:

    > perl -MO=Deparse script_1.pl my(@perls) = (1, 2, 3, 4); sub foo { my(@foo) = @{shift @_;}; return join($/, @foo); } print foo(\@perls); script_1.pl syntax OK > perl -MO=Deparse script_2.pl my(@perls) = (1, 2, 3, 4); sub foo { my(@foo) = @shift; return join($/, @foo); } print foo(\@perls); script_2.pl syntax OK
    -derby
Re: Can someone clarify what's happening here
by biohisham (Priest) on Aug 11, 2010 at 09:07 UTC
    The braces around the prefixes can be done away in this case, so @{array} is the same as @array, ${val} is the same as $val. And this is why @{shift} is made to be an array whose name can also be written as @shift and of course array is not related to the function shift().


    Excellence is an Endeavor of Persistence. A Year-Old Monk :D .