Eli
Eli

Reputation: 38949

How can I shift off a passed array reference directly to an array?

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?

Upvotes: 6

Views: 2816

Answers (5)

Eric Strom
Eric Strom

Reputation: 40142

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.

Upvotes: 6

Ether
Ether

Reputation: 53966

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

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

}

Upvotes: 1

leonbloy
leonbloy

Reputation: 75906

I think this works:

 my @bar = @{(shift)};

Upvotes: 2

Andy Lester
Andy Lester

Reputation: 93666

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]};

Upvotes: 13

Eugene Yarmash
Eugene Yarmash

Reputation: 149796

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

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

Upvotes: 7

Related Questions