Jonathan
Jonathan

Reputation: 177

Selecting Multiple %Hash Elements Using @Array in 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};

Upvotes: 3

Views: 961

Answers (2)

ikegami
ikegami

Reputation: 385809

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;

Upvotes: 4

Borodin
Borodin

Reputation: 126722

I think you want a hash slice, like this

@pets_all{@alive}

although that will give you just a list of the corresponding hash values. To create a second hash that has a subset of the elements in the first, write

my %pets_alive;
@pets_alive{@alive} = @pets_all{@alive};

but if that is your goal then there is probably a better design. Duplicating data structures is rarely necessary or useful

Upvotes: 3

Related Questions