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?
Yes. there is.
my @list = map {
exists $_->{foo} ? $_->{foo} : die 'hashed lacked foo'
}
@hash_list
;
Evan 的回答很接近,但会返回 hashrefs 而不是 foo 的值。
my @list = map $_->{foo} grep { exists $_->{foo} } @hash_list
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 all element of the second argument.
grep is also cool to filter elements in a list and works the same way.
if ( @hash_list != grep { exists $_->{foo} } @hash_list ) {
# test failed
}
If you want to get the values of a hash, use the values()
function. Like this...
print Dumper(values %$hash);
values HASH
In list context, returns a list consisting of all the values of the named hash.
(Source: PerlDoc.org. )
Working Demo Online at: IDEOne
use Data::Dumper;
my $hash = {
soybeans=>1,
chickpeas=>2,
};
print Dumper(values %$hash);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.