Perl - 如果知道值,如何找到哈希的键?

时间:2011-06-21 10:41:00

标签: perl hash

我要做的是检索散列中键值对的键,因为我正在读取的文件中的所有内容都是值。

代码生成如下内容:

12345 welcome.html

这部分的代码是:

my %bugs;
my $bug;
open(FH, '-|', "lynx -dump '$queryurl'") or die "Could not lynx $queryurl: $!";
while (<FH>)
{
    if (/<bz:id[^>]*>([^<]*)</)
    {
        $bug = $1;
    }
    if (/<bz:url[^>]*>([^<]*)</)
    {
        my $url = $1;
        $bugs{$url} = $bug;
        $bug = undef;
    }
}
close(FH);

# for debugging purposes
foreach my $bug (keys %bugs)
{
    print "$bugs{$bug} $bug\n";
}
exit;

然后,在名为bad.txt的文件中的其他位置,我输出如下:

Documents that failed: daerror 6 0 6 welcome.html

读取此文件的代码是:

my $badfile = "$dir/bad.txt";
open(FH, "<$badfile") || die "Can not open $badfile: $!";
# ignore first line
<FH>;
while (<FH>)
{
    chomp;
    if (!/^([^ ]+) [^ ]+ [^ ]+ [^ ]+ ([^ ]+) [^ ]+$/)
    {
        die "Invalid line $_ in $badfile\n";
    }
    my $type = $1;
    my $testdoc = $2;
}

但我已经使用正则表达式从中提取了文件名。

3 个答案:

答案 0 :(得分:10)

您可以使用reverse运算符生成原始哈希的反转副本,然后进行“正常”查找(仅当原始哈希值中的值唯一时才能正常工作)。

有关此主题的更多信息,包括在perlfaq4处理重复值:How do I look up a hash element by value

答案 1 :(得分:5)

my ($key) = grep{ $bugs{$_} eq '*value*' } keys %bugs;
print $key;

答案 2 :(得分:3)

如果您没有使用%bugs哈希,只需修改:

$bugs{$url} = $bug;

为:

$bugs{$bug} = $url;

然后,您将获得一个哈希,其中包含满足查询需求的正确密钥。

相关问题