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 using foreach my %hash = %{$AoH_sorted[$i]}; foreach my $key (keys %hash) { print "$key\t"; } # } print "\n"; }