tags:

views:

100

answers:

5

I have a function (let's call it foo(array_reference, ...)) that expects an array reference among other parameters. I want to have foo shift the array reference off the list of parameters passed to it directly to an array, without having to shift it off as an array reference and then separately convert that to an array.

What I want should be something like: my @bar = @{shift};

What I do not want, but am currently stuck with: my $bar = shift; my @bar = @{$bar}

The latter approach wastes lines, wastes memory, and causes me to hate the writer of this type of Perl code with a fiery passion. Help, please?

+4  A: 

Try my @bar = @{shift()}; or my @bar = @{CORE::shift()};

Perl will warn you that @{shift} is ambigous if you enable warnings with use warnings;.

eugene y
+5  A: 

Do not worry about "wastes lines, wastes memory." Both lines of code and memory are cheap.

You can operate on @_ just like any array, and that includes dereferencing. It sounds like you want one of:

my @bar = @{+shift};
my @bar = @{$_[0]};
Andy Lester
The first one looks like it might be what I want. What's the "+" do?
Eli
@Eli: IIRC, forces scalar context.
Daenyth
@Eli, see "unary +" in perlop: http://perldoc.perl.org/perlop.html#Symbolic-Unary-Operators
friedo
friedo's comment is much more accurate than Daenyth's
ysth
Thanks friedo, that's really helpful.
Eli
+2  A: 

I think this works:

 my @bar = @{(shift)};
leonbloy
+1  A: 

You don't have to explicitly shift your arguments; @_ contains direct aliases to them.

sub my_method
{
    my $this = shift;
    my @array = @{$_[0]};

}
Ether
+3  A: 

Since its not here and I find it the clearest way to disambiguate:

my @bar = @{shift @_}

The reason that each of the answers here adds a non-word character inside the @{ ... } is because inside the brackets, shift is viewed as a unquoted bareword (similar to abc => 1 or $hash{key}). You can add +, ;, (), @_ or other non-word characters to force interpretation as code.

Eric Strom