tags:

views:

88

answers:

3

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} } ...;
+4  A: 

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.

eugene y
Are you saying that the @keys is a new array with just the subset?
Jane
@Jane: yes, correct.
eugene y
+1  A: 

Have a look at perldata, and try something like

foreach (@hash{qw[key1 key2]}) {
    # do something
    }
Nikhil Jain
+4  A: 

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.

FM