martincarlin87
martincarlin87

Reputation: 11062

Perl - How to find the key of a hash if you know the value?

What I am trying to do is retrieve the key of a key value pair in a hash because all I have from a file I am reading in is a value.

The code produces something like this:

12345 welcome.html

The code for this part is:

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;

Then, somewhere else in a file called bad.txt I get output like:

Documents that failed: daerror 6 0 6 welcome.html

The code for reading this file is :

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;
}

But I already have the filename extracted from this using a regular expression.

Upvotes: 6

Views: 12869

Answers (3)

Robie Nayak
Robie Nayak

Reputation: 827

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

Upvotes: 9

Roman Grazhdan
Roman Grazhdan

Reputation: 477

You can make an inverted copy of your original hash with reverse operator and then make a "normal" lookup (would work properly only if values in original hash are unique).

More on this topic including handling duplicate values at perlfaq4: How do I look up a hash element by value

Upvotes: 10

Francisco R
Francisco R

Reputation: 4048

If you aren't using the %bugs hash for anything else, just modify:

$bugs{$url} = $bug;

to:

$bugs{$bug} = $url;

Then you will have a hash with the correct keys to your query needs.

Upvotes: 3

Related Questions