How can I transfer the reference of the passed array directly to the array?

I have a function (let it be called foo($array_reference, ...) ) that expects an array reference among other parameters. I want foo offset the array reference from the list of parameters passed directly to the array, without having to offset it as an array reference, and then separately convert it to an array.

What I want should be something like this:

 my @bar = @{shift}; 

What I don't want, but currently I'm stuck:

 my $bar = shift; my @bar = @{$bar} 

The latter approach takes lines, loses memory, and makes me hate the writer of this type of Perl code with fiery passion. Help me please?

+4
source share
5 answers

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

You can work with @_ just like any array, and which includes dereferencing. It looks like you want one of:

 my @bar = @{+shift}; my @bar = @{$_[0]}; 
+10
source

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

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

+5
source

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

 my @bar = @{shift @_} 

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

+4
source

I think this works:

  my @bar = @{(shift)}; 
+2
source

You do not need to explicitly change your arguments; @_ contains direct aliases.

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

All Articles