Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl, get all hash values

Tags:

list

hash

perl

Let's say in Perl I have a list of hash references, and each is required to contain a certain field, let's say foo. I want to create a list that contains all the mappings of foo. 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 of doing this in Perl?

like image 941
Mike Avatar asked Jun 15 '10 20:06

Mike


People also ask

How print all hash values in Perl?

print "$ perl_print_hash_variable{'-hash_key2'} \n"; Description: The Perl print hash can used $ symbol for a single hash key and its value. The Perl print hash can use the % symbol for multiple hash keys and their values.

How will you get all keys from hashes in Perl and all values from hashes in Perl?

In Perl, hash data structure is provided by the keys() function similar to the one present in Python programming language. This keys() function allows you to get a list of keys of the hash in scalars which can be further used to iterate over the values of respective keys of the hash.

How do you access the elements of a hash in Perl?

Perl Hash Accessing To access single element of hash, ($) sign is used before the variable name. And then key element is written inside {} braces.

What function extracts both keys and values from a hash?

Hash allows to extract these keys and values with the use of inbuilt functions. Getting a list of all of the keys from a hash can be done using keys function.


1 Answers

Yes. there is.

my @list = map {
    exists $_->{foo} ? $_->{foo} : die 'hashed lacked foo'
  }
  @hash_list
;
like image 91
NO WAR WITH RUSSIA Avatar answered Oct 13 '22 23:10

NO WAR WITH RUSSIA