# first get rid of the nuisance "set" keys (i.e. the primary keys of %bighash); # they add nothing to the solution and just get in the way. my %flatten; for my $h ( values %bighash ) { @flatten{ keys %$h } = values %$h; } # now pull out the desired data from %flatten, pack it in records # whose first element is the name of the store, and sort these records # in ascending numerical order according to the [ 1 ][ 0 ]-th element # of each record (which corresponds to the earnings). my @sorted_data = sort { $b->[ 1 ][ 0 ] <=> $a->[ 1 ][ 0 ] } map [ $_, $flatten{ $_ } ], @st; # now it's just a matter of printing the sorted records. for my $record ( @sorted_data ) { print "STORE: $record->[ 0 ] EARNING:$record->[ 1 ][ 0 ]\n"; for my $i ( 1 .. $#{ $record->[ 1 ] } ) { print join( ',', @{ $record->[ 1 ][ $i ] } ), "\n"; } print "\n"; }