2

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?

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Would this work the same? I prefer to use arrow notation: @{ $hashRef->{@keys} }
Ah I see, but this will still be equivalent right: @{ $hashRef }{@keys}
Yup. You've got it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.