in reply to code that fails to act as expected...

foreach $c (each %couples) { print "$c\n"; };

each %couple returns, in list context, the next key/value pair. In this case (bacause the %hash is stored in "semi-random" order), returns the pair (abbot,costello). You can visualize this as:

foreach $c ("abbot","costello") { print "$c\n"; };

The foreach prints then "abbot" and "costello".

The expected output can be obtained in list context, for example:

while (my ($c,$d) = each %couples){ print "$c $d\n"; }

The shorter way I could imagine to do this is:

print "$_ $couples{$_}$/" for (keys %couples);

Hope this helps!

citromatik

Replies are listed 'Best First'.
Re^2: code that fails to act as expected...
by cgmd (Beadle) on Jun 15, 2007 at 11:08 UTC
    Thank you, citromatik. When I implement some of your examples, I notice, now, another baffling action:
    my %couples = ( george => 'gracie', abbot => 'costello', johnson => 'boswell',); while (my($c, $d) = each %couples) { print "$c $d\n"; } print "\n"; foreach my $c (each %couples) { print "$c\n"; } print "\n"; while ( my($c, $d) = each %couples) { print "$d $c\n"; }
    The first foreach example code you offered, when run prior to the first while loop you suggested, causes the while loop to drop one of the key, value pairs.The same while loop, run before the foreach loop, outputs all three key, value pairs.

    What causes that behavior? Does the scope of the foreach loop manage to extend, in some way, to the following while loop?

    Thanks, again, for helping with this.