Boghog has asked for the wisdom of the Perl Monks concerning the following question:
Greetings Monks,
I wanted to sort an array of hashes based on the size of each hash (i.e., the number of the key/value pairs in each hash) using something like:
I wanted to sort an array of hashes based on the size of each hash (i.e., the number of the key/value pairs in each hash) using something like:
However the above script produces the following output which obviously has not been sorted:#!/usr/bin/perl use strict; my @AoH = ( {a => 1, b => 2, c => 3}, {a => 1, b => 2}, {a => 1, b => 2, c => 3, d => 4}, {a => 1} ); my @AoH_sorted = sort { keys(%{$AoH[$b]}) <=> keys(%{$AoH[$a]}) } @AoH +; foreach my $i (0 .. $#AoH_sorted) { print "$i\t"; if (exists $AoH_sorted[$i]) { my %hash = %{$AoH_sorted[$i]}; foreach my $key (keys %hash) { print "$key\t"; } } print "\n"; }
Any ideas on how to get this sort to work? Thanks!0 c a b 1 a b 2 c a b d 3 a
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Sorting an array of hashes
by stiller (Friar) on Mar 26, 2008 at 08:38 UTC | |
by amarquis (Curate) on Mar 26, 2008 at 12:39 UTC | |
by BKB (Novice) on Mar 27, 2008 at 08:23 UTC | |
by stiller (Friar) on Mar 27, 2008 at 08:57 UTC | |
by BKB (Novice) on Mar 27, 2008 at 10:46 UTC | |
by stiller (Friar) on Mar 27, 2008 at 10:57 UTC | |
Re: Sorting an array of hashes
by haoess (Curate) on Mar 26, 2008 at 08:27 UTC | |
Re: Sorting an array of hashes
by admiral_grinder (Pilgrim) on Mar 26, 2008 at 12:49 UTC | |
Re: Sorting an array of hashes
by oko1 (Deacon) on Mar 26, 2008 at 16:46 UTC |
Back to
Seekers of Perl Wisdom