in reply to when do i know that the iterator for a hash was reseted

I see no need to use each in this case:

sub find_in { my ($data_ref, $string) = @_; my $result = 'no result'; my ($key) = grep /^$string$/i, keys %$data_ref; $result = $$data_ref{$key}; return $result; }

Update: condensed and with a modified data set:

sub find_in { my ($data_ref, $string) = @_; return $$data_ref{ (grep /^$string$/i, keys %$data_ref)[0] || '' } + || 'no result'; } sub look_for_data { my %hash = ( A => 'axxx' , B => 'bxxx' , C => 'cxxx' , D => 'dxxx' +); print "d: " . find_in(\%hash , 'd') . "\n"; print "A: " . find_in(\%hash , 'A') . "\n"; print "B: " . find_in(\%hash , 'B') . "\n"; print "Z: " . find_in(\%hash , 'Z') . "\n"; } look_for_data(); __END__ d: dxxx A: axxx B: bxxx Z: no result

Update 2: Added ^ and $ anchors as per jhourcle advice.

Update 3: Same again.

--
David Serrano

Replies are listed 'Best First'.
Re^2: when do i know that the iterator for a hash was reseted
by jhourcle (Prior) on Apr 20, 2006 at 15:12 UTC

    Be careful with that regex:

    (lc($name) eq lc($string)) and ($name =~ /$string/i) are not the same, as the regex will match any occurance of $string within $name (ie, substrings of $name, as well).

    For the original poster -- have you considered using a case insensitive hash? See Tie::CPHash

      thanks for the hint, concerning Tie::CPHash, might save me some work in the future.
Re^2: when do i know that the iterator for a hash was reseted
by Anonymous Monk on Apr 20, 2006 at 13:27 UTC
    Thanks for your answer.
    actually i think there is never a _real_ need to use each, as you can always do it using keys. The thing is i like to use each, because deeply nested hashes tend to get a bit more readable through the use of each (imo).
    But i guess in some cases where i use while each, your code might be a good inspiration.
    By what you and japhy posted, it seems to me that the only reliable way of getting all elements is keys. As with each you will "never know".
    I find it somehow strange that while (my ($key , $val) = each %hash) is the recommended way (perlfaq) for getting all elements from a hash as the behaviour can get so quirky rather quick.