$hash{"0"}=["1","2","15"]; $hash{"1"}=["3","4"]; $hash{"2"}=["5","6"]; $hash{"3"}=["7","8"]; sub expand { my ($key) = @_; if (exists $hash{$key}) { return sort { $a <=> $b } $key, map { expand($_) } @{$hash{$key}} } else { return $key } } my @expanded = map {[ expand $_ ]} @{$hash{0}}; use Data::Dumper; print Dumper(\@expanded); #### sub expand { my ($key) = @_; return sort { $a <=> $b } $key, map { expand($_) } @{$hash{$key}} } #### sub e{@_,map{e($_)}@{@hash{@_}}} print Dumper[map{[sort{$a<=>$b}e$_]}@{$hash{0}}]