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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |