Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a large Perl hash, how do I extract a subset of particular keys?

Tags:

key

hash

perl

I have a large hash and have a subset of keys that I want to extract the values for, without having to iterate over the hash looking for each key (as I think that will take too long).

I was wondering if I can use grep to grab a file with a subset of keys? For example, something along the lines of:

 my @value = grep { defined $hash{$_}{subsetofkeysfile} } ...;
like image 828
Jane Avatar asked Dec 17 '22 21:12

Jane


2 Answers

Use a hash slice:

my %hash = (foo => 1, bar => 2, fubb => 3);
my @subset_of_keys = qw(foo fubb);
my @subset_of_values = @hash{@subset_of_keys};  # (1, 3)

Two points of clarification. (1) You never need to iterate over a hash looking for particular keys or values. You simply feed the hash a key, and it returns the corresponding value -- or, in the case of hash slices, you supply a list of keys and get back a list of values. (2) There is a difference between defined and exists. If you're merely interested in whether a hash contains a specific key, exists is the correct test.

like image 167
FMc Avatar answered Dec 19 '22 11:12

FMc


If the hash may not contain any keys from the subset, use a hash slice and grep:

my @values = grep defined, @hash{@keys};

You can omit the grep part if all keys are contained in the hash.

like image 35
Eugene Yarmash Avatar answered Dec 19 '22 11:12

Eugene Yarmash