Alfons
Alfons

Reputation: 331

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 take the value of B of hash{ 1 }?

$hashtest{'B'}{1}

Upvotes: 0

Views: 3379

Answers (6)

Zaid
Zaid

Reputation: 37136

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'

Upvotes: 0

Alan Haggai Alavi
Alan Haggai Alavi

Reputation: 74202

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.

Upvotes: 0

Toto
Toto

Reputation: 91373

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

Upvotes: 3

bob.faist
bob.faist

Reputation: 728

$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";

Upvotes: 1

toolic
toolic

Reputation: 62002

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)

Upvotes: 3

ghostdog74
ghostdog74

Reputation: 342273

$hashtest{1}{1};

Upvotes: -1

Related Questions