Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quickly filter a perl hash of hashes

Tags:

hash

filter

perl

I have a perl hash of hashes like the following:

$VAR1 = {
          'ID_1' => {
                           'FILE_B' => '/path/to/file/file1',
                           'FILE_C' => '/path/to/file/file2',
                           'FILE_A' => '/path/to/file/file3'
                         },
          'ID_2' => {
                           'FILE_B' => '/path/to/file/file4',
                           'FILE_A' => '/path/to/file/file5'
                         },
          'ID_3' => {
                           'FILE_B' => '/path/to/file/file6',
                           'FILE_A' => '/path/to/file/file7'
                         }
          ...                       
}

I would like to get a list of all keys of members in the main hash that have FILE_C defined. In the example, this will return only ID_1.

I know how to do this in a cumbersome loop (iterating all keys, checking if FILE_C is defined, if so — pushing the key to an array, finally returning this array), but I have a feeling there's a single-liner or even a function for this …

like image 880
David B Avatar asked Sep 06 '10 07:09

David B


1 Answers

Yep, perl has the grep function:

my @keys = grep { defined $hash{$_}{FILE_C} } keys %hash;

like image 197
Eugene Yarmash Avatar answered Nov 04 '22 03:11

Eugene Yarmash