如何有效地从引用的散列和perl中的键数组中获取值数组?

时间:2023-01-05 13:36:15

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 个解决方案

#1


5  

Easily:

很容易:

my @values = @$hashRef{@keys};

Or, on Perl 5.24+:

或者,在Perl 5.24 +:

my @values = $hashRef->@{@keys};

Or, on Perl 5.20+ by enabling some additional features:

或者,在Perl 5.20+上通过启用一些附加特性:

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.

这利用了以下事实:您可以使用@hash{LIST}语法获得%散列的多个键(一个“片”)的值。你只要先把它去掉。更多信息请参见perldoc。

#1


5  

Easily:

很容易:

my @values = @$hashRef{@keys};

Or, on Perl 5.24+:

或者,在Perl 5.24 +:

my @values = $hashRef->@{@keys};

Or, on Perl 5.20+ by enabling some additional features:

或者,在Perl 5.20+上通过启用一些附加特性:

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.

这利用了以下事实:您可以使用@hash{LIST}语法获得%散列的多个键(一个“片”)的值。你只要先把它去掉。更多信息请参见perldoc。