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?
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]};
Try my @bar = @{shift()};
or my @bar = @{CORE::shift()};
Perl will warn you that @{shift}
is ambigous if you enable warnings with use warnings;
.
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.
I think this works:
my @bar = @{(shift)};
You don't have to explicitly shift your arguments; @_
contains direct aliases to them.
sub my_method
{
my $this = shift;
my @array = @{$_[0]};
}
精彩评论