Reputation: 393
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} } ...;
Upvotes: 4
Views: 2938
Reputation: 8342
Have a look at perldata, and try something like
foreach (@hash{qw[key1 key2]}) {
# do something
}
Upvotes: 1
Reputation: 42421
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.
Upvotes: 7
Reputation: 149873
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.
Upvotes: 4