Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

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

by mr_mischief (Monsignor)
on Dec 03, 2015 at 19:22 UTC ( #1149332=note: print w/replies, xml ) Need Help??


in reply to Re^3: 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

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.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2022-12-09 23:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?