in reply to Foreach syntax

Any time you find yourself looking up a hash value for each key of a hash, don't forget the appropriately named each function.

while (my ($p9, $is_available) = each %is_available) { next if !$is_available; # do something with each available $p9 }

The foreach (keys) iteration walks through the hash but averts its eyes from the values. The while (($key, $value) = each) iteration sensibly says we may as well grab the value while we're in the neighborhood.

Replies are listed 'Best First'.
Re^2: Foreach syntax - don't forget the each function!
by FunkyMonk (Bishop) on Jul 25, 2008 at 22:21 UTC
    Always think twice before using each. If you exit the loop early the iterator will not be reset if you enter the loop again:

    my %hash = qw/ one 1 two 2 three 3 four 4 five 5 /; print "pass 1-----\n"; once_thru(); print "pass 2-----\n"; once_thru(); sub once_thru { while ( my ( $k, $v ) = each %hash ) { last if $k eq 'five'; print "$k $v\n"; } } __END__ pass 1----- three 3 pass 2----- one 1 two 2 four 4

    From each:

    There is a single iterator for each hash, shared by all "each", "keys", and "values" function calls in the program; it can be reset by reading all the elements from the hash, or by evaluating "keys HASH" or "values HASH".
    The pitfalls could be made much clearer, IMHO.

    Unless I state otherwise, all my code runs with strict and warnings