Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting Multiple %Hash Elements Using @Array in Perl

Tags:

arrays

hash

perl

How does one create a new hash using an array of keys on an existing hash?

my %pets_all = ( 

    'rover' => 'dog',
    'fluffy' => 'cat',
    'squeeky' => 'mouse'
);

my @alive = ('rover', 'fluffy');

#this does not work, but hopefully you get the idea.
my %pets_alive = %pets_all{@alive};
like image 374
Jonathan Avatar asked May 03 '26 01:05

Jonathan


1 Answers

my %pets_alive = %pets_all{@alive}; is called a key/value hash slice, and it actually does work since recently-released 5.20.

Before 5.20, you have a couple of alternatives:

  • my %pets_alive; @pets_alive{@alive} = @pets_all{@alive}; (Hash slices)

  • my %pets_alive = map { $_ => $pets_all{$_} } @alive;

like image 129
ikegami Avatar answered May 05 '26 15:05

ikegami