Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Sorting an array of hashes

by stiller (Friar)
on Mar 26, 2008 at 08:38 UTC ( #676333=note: print w/replies, xml ) Need Help??


in reply to Sorting an array of hashes

You should try use diagnostics; when things get tough, and use warnings; unless you really know you wont need it (you seldom can know that), but the hints use warnings and diagnostics would give here isn't trivial to understand.
You are just overdoing your sort criteria:
use strict; use warnings; 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(%{$b})) <=> (keys(%{$a})) } @AoH; foreach my $i (0 .. $#AoH_sorted) { print "$i\t"; # if (exists $AoH_sorted[$i]) { # no need to check if exist when usi +ng foreach my %hash = %{$AoH_sorted[$i]}; foreach my $key (keys %hash) { print "$key\t"; } # } print "\n"; }

gives:
0 c a b d 1 c a b 2 a b 3 a

Replies are listed 'Best First'.
Re^2: Sorting an array of hashes
by amarquis (Curate) on Mar 26, 2008 at 12:39 UTC

    It took me a bit to understand the error/solution myself here. $a and $b are set to elements of @AoH, not indexes of @AoH, so there is no need to look up the element as in %{$AoH[$b]}, you just directly dereference the hash reference directly as %{$b}, correct?

    I agree on the use warnings; as that 'Use of reference "HASH(########)" as array index at myscript.pl' saves me from my own novice-ness constantly.

Re^2: Sorting an array of hashes
by BKB (Novice) on Mar 27, 2008 at 08:23 UTC
    # no need to check if exist when using foreach
    #! perl use warnings; use strict; my @x = (1,2,3,4,5); delete $x[2]; for (0..4) { print $x[$_] }
      Actually, in that case you need to check if the value is defined. The element still exists, and checking for existens doesn't buy you anything.
        Running the previous version of code:
        perl arraydelete.pl Use of uninitialized value within @x in print at arraydelete.pl line 6 +. 1245
        Modified as follows using "exists":
        #! perl use warnings; use strict; my @x = (1,2,3,4,5); delete $x[2]; for (0..4) { print $x[$_] if exists ($x[$_]) }
        Run it to produce:
        perl arraydelete.pl 1245

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2020-08-13 20:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Which rocket would you take to Mars?










    Results (75 votes). Check out past polls.

    Notices?