简体   繁体   中英

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};

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM