Perl, get all hash values

Let's say in Perl I have a list of hash links, and each one should contain a specific field, say foo . I want to create a list containing all foo mappings. If there is a hash that does not contain foo , the process should fail.

 @hash_list = ( {foo=>1}, {foo=>2} ); my @list = (); foreach my $item (@hash_list) { push(@list,$item->{foo}); } #list should be (1,2); 

Is there a more concise way to do this in Perl?

+7
list perl hash
source share
4 answers

Yes. there is.

 my @list = map { exists $_->{foo} ? $_->{foo} : die 'hashed lacked foo' } @hash_list ; 
+6
source share

You can use the map function for this:

 @hash_list = ( {foo=>1}, {foo=>2} ); @list = map($_->{foo}, @hash_list); 

map applies the function in the first argument over the entire element of the second argument.

grep also cool filters the items in the list and works the same way.

+2
source share

Evan's answer is close, but will return hashrefs, not foo.

 my @list = map $_->{foo} grep { exists $_->{foo} } @hash_list 
+1
source share
 if ( @hash_list != grep { exists $_->{foo} } @hash_list ) { # test failed } 
0
source share

All Articles