Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re^2: How to Sort a Hash According to the Keys in the Hash

by AnomalousMonk (Archbishop)
on Dec 02, 2015 at 19:18 UTC ( [id://1149206]=note: print w/replies, xml ) Need Help??


in reply to Re: How to Sort a Hash According to the Keys in the Hash
in thread How to Sort a Hash According to the Keys in the Hash

... sort keys %my_hash ...

My first thought too, but ishootperls seems to want to recover the insertion order of the keys into the hash, which, per choroba above, is available through something like Tie::IxHash.


Give a man a fish:  <%-{-{-{-<

Replies are listed 'Best First'.
Re^3: How to Sort a Hash According to the Keys in the Hash
by Discipulus (Canon) on Dec 02, 2015 at 21:32 UTC
    ..or by hardcoding the order into an array and use this array to generate the hash:
    my @order = qw(Sports Books Places); my %hash; # populate the hash's slice @hash{@order} = ( # we need a list # of three anonymous array ["Soccer","UltimateFrisbee","Basketball"], ["Cannery Row", "Animal Farm", "East of Eden"], ["BigSur","Zion", "CrateLake"] ); #retrieve them in the desired @order print map { "$_ => ".(join ',',@{$hash{$_}})."\n" } @order ;


    array are good to have things ordered, queue and series
    hashes are better to count things or have list of uniques, or general associations.

    sort can accept a block of code to do your custom sort but is impossible for sort to know a priori the order followed while inserting values, because hashes are unsorted, by definition.

    L*
    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

      An alternative to keeping a separate data structure about your data structure is to create another layer within the existing one. It may make it clearer at a glance which list goes with which list title and make it more maintainable as well.

      In this case since we want sorting of the keys of a hash which has values of arrays, I suggest an array of hashes of arrays.

      use strict; use warnings; my @array = ( # we need a list { 'Sports' => [ 'Soccer', 'Ultimate Frisbee', 'Basketball' ], }, { 'Books' => [ 'Cannery Row', 'Animal Farm', 'East of Eden' ], }, { 'Places' => [ 'BigSur', 'Zion', 'Crater Lake' ], }, # of name/value pairs # which contain lists as their values ); # you could do this foreach my $hr ( @array ) { my $key = (keys %$hr)[0]; print "$key => " . ( join ', ', @{ $hr->{ $key } } ) . "\n"; } # or maybe this is clearer print "\n"; foreach my $hr ( @array ) { my ( $k, $list ) = each %$hr; print "$k => " . ( join ', ', @$list ) . "\n"; } # or if you really like map print "\n"; print map { (keys $_)[0] . ' => ' . ( join ', ', @{ $_->{ (keys $_)[0] + } } ) . "\n" } @array; # or this print "\n"; print map { my ( $k, $v ) = each %$_; $k . ' => ' . ( join ', ', @$v ) + . "\n" } @array; # or maybe this print "\n"; print map { my $k = (keys %$_)[0]; my $v = join ', ', @{ (values %$_)[ +0] }; "$k => $v\n" } @array; # or maybe even this print "\n"; print map { (keys $_)[0] . ' => ' . ( join ', ', @{ (values %$_)[0] } +) . "\n" } @array;

      What I'd really hate to do, though, is have to keep counting items in the hash and items in the separate array to make sure I'm maintaining the right list six months from now. If you're trying to use arrays rather than pull in ordered hash modules, then the proper place for the array is likely in the same data structure as the hash.

Re^3: How to Sort a Hash According to the Keys in the Hash
by andal (Hermit) on Dec 03, 2015 at 07:29 UTC

    No, you misunderstood him (or he misunderstood you :) sort is applied to the list of of keys returned by keys (the keys returns list in random order). So your foreach loop shall iterate over sorted list of keys. You then use current key to obtain value from hash. If you shall access your hash only ones, then you can use this approach. If there are multiple accesses, then it makes sense to keep sorted list of keys to avoid sorting multiple times.

    On a side note. Your code in the original message contains error. You use variable $keyHoA as iterator of the loop, but to access value of the hash inside of the loop you use variable $req ($newHoA{$req}[0])

      I'm not sure to whom this reply was intended to be addressed. I don't think it was to me.


      Give a man a fish:  <%-{-{-{-<

        Hm. I was replying to comment about using "sort keys". Somehow I understood your words so, that you didn't think that this method is acceptable. Sorry.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (4)
As of 2024-04-25 13:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found