Perl如何将哈希值与列表进行比较并返回匹配的键

王云龙*_*王云龙 -1 perl hash

考虑这种情况:我有一个列表:

@Value2CompareList
Run Code Online (Sandbox Code Playgroud)

我有一个哈希表:

%Hash2Check
Run Code Online (Sandbox Code Playgroud)

现在我想实现以下目标:

if($Hash2Check{$keys} eq $ElementFromArray) {return matching keys}
Run Code Online (Sandbox Code Playgroud)

如何在没有Loop的情况下更快地完成这项工作?

谢谢大家!

cho*_*oba 5

你可以在grep中使用grep:

#! /usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

my @Value2CompareList = qw( a b c d e f );
my %Hash2Check = (
    A => 'a',
    B => 'b',
    C => 'c');

say for grep {
    my $k = $_;
    grep $Hash2Check{$k} eq $_, @Value2CompareList
} keys %Hash2Check;
Run Code Online (Sandbox Code Playgroud)

这很复杂,因为数据结构不适合您的需要.反向散列会更好:

my %Inverted = reverse %Hash2Check;
say for grep defined, @Inverted{@Value2CompareList};
Run Code Online (Sandbox Code Playgroud)

仅当值是唯一的时才有效.如果没有,则需要创建数组哈希:

my %Inverted;
while (my ($k, $v) = each %Hash2Check) {
    push @{ $Inverted{$v} }, $k;
}
say for map @$_, grep defined, @Inverted{@Value2CompareList};
Run Code Online (Sandbox Code Playgroud)