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

hi monks, I am a beginner in perl and I am a bit confused.my problem is that i need to traverse the whole hash and match a particular key and corresponding to that key i need a value and store that value in a variable.I think it must be clear now
  • Comment on how to get a value corresponding to a key

Replies are listed 'Best First'.
Re: how to get a value corresponding to a key
by dorward (Curate) on Jul 20, 2005 at 11:58 UTC

    Why do you need to traverse the entire hash? Just go directly to that key.

    my %hash = (foo => 'bar', baz => 'biff'); my $scalar = $hash{foo};

    You should probably read perldoc perldata.

Re: how to get a value corresponding to a key
by anonymized user 468275 (Curate) on Jul 20, 2005 at 12:20 UTC
    The term 'traverse', strongly suggests a recursive search of a hash of hash of ... of hash.
    Traverse( \%yourhash, \$output, 'matchKey' ); sub Traverse{ my $href = shift; my $oref = shift; my $match = shift; for my $key ( keys %$href ) { if ( ref( $href -> { $key }) eq 'HASH') { Traverse( $href -> { $key }, $oref ); } else { ( $key eq $match ) and $$oref = $href -> { $key }; } } }

    One world, one people

Re: how to get a value corresponding to a key
by prasadbabu (Prior) on Jul 20, 2005 at 11:57 UTC

    What you have tried so far? You should go through perldata. Here is a small example.

    %hash =("name" =>"john", "age"=>"25", "job"=>"programer", "location"=> +"US"); while (($key, $val) = each %hash) { if ($matchkey =~ /^$key$/) #if matches the particular key { $var = $hash{$key}; } }

    or even simply,

    $matchkey eq $_ ? $var = $hash{$_} : $var='' for keys %hash;

    still simply as davorg suggested

    $var = $hash{$matchkey}

    updated

    Prasad

      That seems rather a long way to go about it. What does your method give you that simply using $var = $hash{$matchkey} doesn't?

      Also why use $matchkey =~ /^$key$/ when $matchkey eq $key achieves the same thing without the overhead of invoking the regex engine? Regular expressions are a powerful tool, but they are often unnecessarily complex for the task in hand.

      --
      <http://www.dave.org.uk>

      "The first rule of Perl club is you do not talk about Perl club."
      -- Chip Salzenberg