#!/usr/bin/perl use strict; use warnings; my %sorthash = (); $sorthash{'10'}{'20'}= '1'; $sorthash{'40'}{'50'}= '4'; $sorthash{'20'}{'30'}= '2'; # Invert the hash my %reverse_hash = (); for my $keys1 (keys %sorthash ) { my $child_hashref = $sorthash{$keys1}; for my $keys2 (keys %$child_hashref ) { $reverse_hash{$keys2}{$keys1} = $child_hashref->{$keys2}; } } # Print after sorting keys for my $keys2 (sort {$a <=> $b} keys %reverse_hash) { my $child_hashref = $reverse_hash{$keys2}; for my $keys1 (sort {$a <=> $b} keys %$child_hashref) { print "keys: $keys1\t$keys2\t"; print "values: $child_hashref->{$keys1}\n"; } }