Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: While on hashes doesn't work?

by mkmcconn (Chaplain)
on Feb 04, 2002 at 23:26 UTC ( [id://143316]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://143316]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2024-04-23 07:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found