Reputation: 323
I currently have an referenced hash and an array of keys that the hash contains. I want to get an array of the values corresponding to my array of keys.
I know how to do this in multiple lines:
# Getting hash reference and array of keys.
my $hashRef = {
one => 'foo',
two => 'bar',
three => 'baz'
};
my @keys = ('one', 'three');
# Getting corresponding array of values.
my @values;
foreach my $key (@keys) {
push @values, $hashRef->{$key};
}
However, I believe that there must be a much better way that doesn't make use of a loop. But unfortunately I just can't figure it out. How can I efficiently get an array of values from a referenced hash and an array of keys; ideally in one line if possible?
Upvotes: 2
Views: 57
Reputation: 8467
Easily:
my @values = @$hashRef{@keys};
Or, on Perl 5.24+:
my @values = $hashRef->@{@keys};
Or, on Perl 5.20+ by enabling some additional features:
use feature qw(postderef);
no warnings qw(experimental::postderef);
my @values = $hashRef->@{@keys};
This takes advantage of the fact that you can get the values for multiple keys (a "slice") of a %hash
with the @hash{LIST}
syntax. You just have to dereference it first. See perldoc for more information.
Upvotes: 5