开发者

Quickly filter a perl hash of hashes

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 …


Yep, perl has the grep function:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜