$ perl -Mstrict -Mwarnings -E ' sub print_outside_loop { print "@_\n" } my %a=(); $a{1}{"a"}{"A"}="FIRST"; $a{1}{"c"}{"B"}="THIRD"; $a{1}{"b"}{"C"}="SECOND"; foreach my $k1 ( sort keys %a ) { foreach my $k2 ( sort keys %{$a{$k1}} ) { foreach my $k3 ( sort keys %{$a{$k1}{$k2}} ) { print_outside_loop($a{$k1}{$k2}{$k3}); } } } ' FIRST SECOND THIRD