How do I access keys by value in a Perl hash of hashes?
I've hash of hash like this:
$hashtest{ 1 } = {
0 => "A",
1 => "B",
2 => "C"
};
For example, how can I tak开发者_JAVA百科e the value of B of hash{ 1 }?
$hashtest{'B'}{1}
Others have provided the proverbial fish
Perl has free online (and at your command prompt) documentation. Here are some relevant links:
perldoc perlreftut
perldoc perldsc
References Quick Reference (PerlMonks)
According to your comment on other responses, you can reverse the hash (ie. exchange keys and values).
But be carefull to do this only if you are sure there are no duplicate values in the original because this operation keep only one of them.
#!/usr/bin/perl
use 5.10.1;
use warnings;
use strict;
my %hashtest;
$hashtest{ 1 } = { 0 => "A", 1 => "B", 2 => "C" };
my %rev = reverse %{$hashtest{1}};
say $rev{B};
Output:
1
$hashtest{ 1 } = { 0 => "A", 1 => "B", 2 => "C" };
my $index;
my $find = "B";
foreach my $key (keys %{ $hashtest{1} }) {
if($hashtest{1}{$key} eq $find) {
$index = $key;
last;
}
}
print "$find $index\n";
Since you have used numbers for your hash keys, in my opinion, you should be using an array instead. Else, when reversing the hash, you will lose duplicate keys.
Sample code:
use strict;
use warnings;
use List::MoreUtils 'first_index';
my $find = 'A';
my @array = qw{ A B C };
my $index = first_index { $_ eq $find } @array;
Perl Data Structures Cookbook will help you understand the data structures in Perl.
If all of your keys are integers, you most probably want to deal with arrays and not hashes:
$array[1] = [ qw( A B C ) ]; # Another way of saying [ 'A', 'B', 'C' ]
print $array[1][1]; # prints 'B'
$hashtest{1}{1};
精彩评论