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

What I'm trying to do is get the key of the key value pair in the hash, because all I have from the file I'm reading is the value.

The code creates something like this:

12345 welcome.html

Code for this part:

 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, for example:

Documents that failed: daerror 6 0 6 welcome.html

Code for reading this file:

 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 a file name extracted from this using a regular expression.

+6
source share
3 answers

If you are not using the %bugs hash for anything else, just change:

 $bugs{$url} = $bug; 

in

 $bugs{$bug} = $url; 

You will then have a hash with the correct keys for your requests.

+3
source

You can make an inverted copy of the original hash with the reverse operator, and then do a β€œnormal” search (it will work correctly only if the values ​​in the original hash are not unique).

More on this topic, including handling duplicate values ​​in perlfaq4: How to find a hash element by value

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

Source: https://habr.com/ru/post/891001/


All Articles