Zaxo's answer is good if you don't need to know which key had a value that matched. In general, you loop over a hash in one of these ways:
for my $value (values %hash) { # do something with $value } for my $key (keys %hash) { # do something with $key and $hash{$key} } # same as above, but sorted by value (or whatever) for my $key (sort { $hash{$a} cmp $hash{$b} } keys %hash) { } # with a while loop, you can bail out early without having # loaded all the keys on the stack up front; may be # more efficient for a large hash, or one tied to a dbm file. while (my $key = each %hash) { # note that there's an implicit defined() on the above assignment, # so the while loop continues to until each() returns undef # even if there are "0" or "" keys # do something with $key and $hash{$key} } # same as above, but go ahead and let list-context each # give both the key and the value while (my ($key, $value) = each %hash) { # above is a list assignment in scalar context, which evaluates to # the number of elements on the right of the assignment. # as long as each returns more data, the assignment will evaluate t +o 2 (true) # When the end is reached, each returns an empty list so the assign +ment # evaluates to 0. # do something with $key and $value }

In reply to Re: Iterating over hash contents? by ysth
in thread Iterating over hash contents? by Spidy

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.