in reply to While on hashes doesn't work?

Not recommending it, but perhaps it gives insight into how while works (in addition to what gellyfish said above)

#!/usr/bin/perl -w use strict; my %data = ( a01 => "two", a02 => "peas", a03 => "in", a04 => "a", a05 => "pod." ); while (($_) = sort keys %data){ print "while: $data{$_}\n"; delete $data{$_}; } print "while loop terminates because", "%data is now empty >", %data,"< \n"; __END__

Without those parens around $_, I would expect it to try to pass '5' into the block (which it would do if you took away the sort function), but it doesn't do that. I suppose that might qualify as an insignificant bug.
update: thanks to merlyn for fixing the bug in my understanding of how sort behaves.
mkmcconn </code>

Replies are listed 'Best First'.
Re: Re: While on hashes doesn't work?
by merlyn (Sage) on Feb 04, 2002 at 23:38 UTC
    while (($_) = sort keys %data){ print "while: $data{$_}\n"; delete $data{$_}; }
    This is a pretty expensive loop. You'd be much better doing:
    while (my ($k, $v) = each %data) { print "key is $k, value is $v\n"; }
    Without those parens around $_, I would expect it to try to pass '5' into the block (which it would do) if you took away the sort function, but it doesn't do that. I suppose that might qualify as an insignificant bug.
    No, sort in a scalar context always returns undef. Maybe someday, it'll return something useful. But not yet. No bug, except in perhaps your understanding. {grin}

    -- Randal L. Schwartz, Perl hacker