#!/usr/bin/perl use strict; use warnings; my $VAR1 = { '212' => { '42' => 6, '49' => 6, '41' => 1 }, '282' => { '38' => 4, '39' => 1, '37' => 2 } }; my %reg = %{$VAR1}; my $c = 1; # sort by the item with the most sub-keys first # if there is a tie sort by sub-keys foreach my $item (sort { scalar keys (%{$reg{$b}})<=>scalar keys (%{$reg{$a}}) || $a<=>$b } keys %reg){ foreach my $case (sort {$reg{$item}{$a}<=>$reg{$item}{$b}} keys %{$reg{$item}}){ print "$c = $item:$case\n"; $c++; } }