Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, Below is a piece of code that reads from a file and builds a hash:
#!/usr/bin/perl %Test_hash=(); open(F, "xfile.test"); while ($line=<F>){ if ($line=~ /FIRST/) { ($Test_num,$Test)=(split(/\s+/,$line))[0,2]; push (@Tests,$Test); @all_me=(); } if ($line=~ /SUBSET/ ) { $me=(split(/\s+/,$line))[2]; push(@all_me,$me); $Test_hash{$Test} = [@all_me]; } } use Data::Dumper; print Dumper([\%Test_hash]); __DATA__ <xfile.test> FIRST ONE TEST1 SUBSET a.me SUBSET b.me SUBSET c.me
The hash is something like TEST1 (key) - all *.me's as values. I am looking at passing *.me as an argument and it should return the corresponding key. HELP!!??? Thanks

Replies are listed 'Best First'.
Re: Return value given a key
by Perl Mouse (Chaplain) on Nov 22, 2005 at 11:20 UTC
    You title suggest you have a key, and want a value, but your question is actually the other way around.

    The answer is that if you want to find a key belonging to a certain value, you should have used a different datastructure. In a hash, keys are unique, values don't have to. The entire point of a hash is to be able to search with keys - if you want to search with the values, you should have used the values as the keys, and the keys as the values.

    Perl --((8:>*
      Or, if you want to speed up looking for a value, build an inverse hash..
      my %forwardhash = ( key1 => 'value1', key2 => 'value2', key3 => 'value3' ); my %reversehash = (); while ( my ( $key, $value ) = each %forwardhash ) { $reversehash{$value} = $key; } use Data::Dumper; print Dumper( \%reversehash );

      Outputs:

      $VAR1 = { 'value1' => 'key1', 'value2' => 'key2', 'value3' => 'key3' };