How to extract multiple values from a perl hashref?

333 Views Asked by At

How can I unpack a Perl hashref into multiple named scalar variables?

I've seen it done but can't seem to make it work.

Assuming the $hashref as given, and the definition of $arg1 to $arg3, here's my attempt:

my $hashref = { arg1 => 'val1', arg2 => 'val2', arg3 => 'val3',};
my ($arg1,$arg2,$arg3) = @{%$hashref}[qw(arg1 arg2 arg3)]; 
1

There are 1 best solutions below

1
JGNI On BEST ANSWER

You need this

my ($arg1,$arg2,$arg3) = @{$hashref}{qw(arg1 arg2 arg3)};

Which is a hash slice against a hash ref