Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

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?

like image 259
Eli Avatar asked Oct 20 '10 17:10

Eli


People also ask

How do you shift elements in an array?

Create a temp variable and assign the value of the original position to it. Now, assign the value in the new position to original position. Finally, assign the value in the temp to the new position.

What does shifting an array mean?

shift() The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.


2 Answers

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]};
like image 63
Andy Lester Avatar answered Nov 15 '22 00:11

Andy Lester


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

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

like image 26
Eugene Yarmash Avatar answered Nov 15 '22 00:11

Eugene Yarmash