2

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)]; 
ggorlen
  • 44,755
  • 7
  • 76
  • 106
null
  • 889
  • 1
  • 13
  • 24
  • 1
    Apparently I asked the same question 7 years ago - here https://stackoverflow.com/questions/13657103 – null Nov 21 '19 at 00:13

1 Answers1

5

You need this

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

Which is a hash slice against a hash ref

JGNI
  • 3,933
  • 11
  • 21