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.
|