Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

something weird in this hash sorting

by Sombrerero_loco (Beadle)
on Jan 15, 2009 at 11:46 UTC ( [id://736516]=perlquestion: print w/replies, xml ) Need Help??

Sombrerero_loco has asked for the wisdom of the Perl Monks concerning the following question:

Hi again. I have the next hash:
%name {11} {key2}
           {key2}
           {key2}
      {2}  {key2}
      {10} {key2}
      {1}  {key2}
           {key2}
      {5}  {key2}
           {key2}

This its the order the data has been stored in my hash. After that using this code:
foreach $ctrl_2 (sort keys (%final)) {
	print "level-> $ctrl_2\n";}
the script returns to me the next output:
level-> 1
level-> 10
level-> 11
level-> 2
level-> 5
You dont think this its really weird? i think its something related to how perl do this function...but i think also there's another way to fix this. Thanks!

Replies are listed 'Best First'.
Re: something weird in this hash sorting
by borisz (Canon) on Jan 15, 2009 at 11:57 UTC
    you must sort the keys numerical. try:
    for my $ctrl_2 ( sort { $b <=> $a } keys (%final) ){ ... }
    and read perldoc -f sort for more information.
    Boris
      Hi boris. Thanks it works. also thanks to everybody. cheers
Re: something weird in this hash sorting
by johngg (Canon) on Jan 15, 2009 at 11:56 UTC

    Put use Data::Dumper; at the top of your script and, after you have created your %name hash, put these lines

    print Data::Dumper->Dump( [ \ %name ], [ qw{ *name } ] ); exit;

    and see whether the contents of the hash are what you expected. Another thing, your hash is, apparently, %name but you sort keys (%final). Some discrepancy there!

    I hope this helps you.

    Cheers,

    JohnGG

Re: something weird in this hash sorting
by Bloodnok (Vicar) on Jan 15, 2009 at 17:27 UTC
    If you need the keys returned in insertion order, see Recipe 5.6 in the Perl Cookbook ... which uses Tie::IxHash.

    A user level that continues to overstate my experience :-))

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (7)
As of 2024-03-29 15:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found