按值进行简单哈希搜索

时间:2011-11-22 03:03:26

标签: perl search hash grep

我有一个简单的哈希,并希望根据$ value条件返回$ key。也就是说,对于第14行,我需要返回$ key为“黄色”的$ key的代码?

1  #!/usr/bin/perl
2
3  # This program creates a hash then
4  # prints out what is in the hash
5
6  %fruit = (
7   'apple' => ['red','green'],
8   'kiwi' => 'green',
9   'banana' => 'yellow',
10  );
11
12 print "The apple is @{$fruit{apple}}.\n";
13 print "The kiwi is $fruit{kiwi}.\n";
14 print "What is yellow? ";

5 个答案:

答案 0 :(得分:21)

grep是这项工作的正确工具:

my @all_matches = grep { $fruit{$_} eq 'yellow' } keys %fruit;
print("$_ ") foreach @matching_keys;

my ($any_match) = grep { $fruit{$_} eq 'yellow' } keys %fruit;

答案 1 :(得分:2)

我不太确定使用单向哈希很容易做到。哈希的重点是将密钥转换为值(如果您在封面下查看,则将值转换为值的位置)。您可以对所有值进行详尽的搜索,随时收集密钥,但这不如哈希查找有效。

为了有效地转向 ,您可能需要考虑双向哈希,例如:

%fruit = (
    'apple' => ['red','green'],
    'kiwi' => 'green',
    'banana' => 'yellow',
);
%antifruit = (
    'red' => 'apple',
    'green' => ['apple','kiwi'],
    'yellow' => 'banana',
);
print "The apple is @{$fruit{'apple'}}.\n";
print "The kiwi is $fruit{'kiwi'}.\n";
print "A yellow thing is $antifruit{'yellow'}.\n";

答案 2 :(得分:1)

sub find_key { 
    my ( $h, $value ) = @_;
    while ( my ( $k, $v ) = each %$h ) { 
        return $k if $v eq $value;
    }
    return;
}

所以你可以这样称呼它:

find_key( \%fruit, 'yellow' );

答案 3 :(得分:1)

由于您的某些值是数组,因此需要检查它。

<强>调用

my @fruit = getfruit(\%fruit, $colour);

子程序:

sub getfruit {
    my ($fruit, $col) = @_;
    my @result;
    for my $key (keys %$fruit) {
        if (ref $fruit->{$key} eq 'ARRAY') {
            for (@{$fruit->{$key}}) {
                push @result, $key if /^$col$/i;
            }
        } else {
            push @result, $key if $fruit->{$key} =~ /^$col$/i;
        }
    }
    return @result;
}

使用正则表达式而不是eq是可选的,只要注意保持相同的情况,因为Yellowyellow被视为不同的键。

答案 4 :(得分:0)

我注意到你的例子引用了匿名数组,所以我只想做一个冗长的foreach / if循环:

my %fruit = (
  'apple' => ['red','green'],
  'kiwi' => 'green',
  'banana' => 'yellow',
);

print "The apple is @{$fruit{apple}}.\n";
print "The kiwi is $fruit{kiwi}.\n";
print "What is yellow? ";

my $ele;
my $search = 'yellow';
my @match = ();

foreach $ele (keys(%fruit)) {
    if(ref($fruit{$ele}) eq 'ARRAY' and
        grep { $_ eq $search } @{ $fruit{$ele} }) {
        push(@match, $ele);
    } elsif(!ref($fruit{$ele}) and $fruit{$ele} eq $search) {
        push(@match, $ele);
    }
}
print join(", ", @match) . "\n";