#!/usr/bin/perl -w $hash{"0"} = ["1","2","15"]; $hash{"1"} = ["3","4"]; $hash{"2"} = ["5","6"]; $hash{"3"} = ["7","8"]; # Recursively expand a key in the hash into itself and its values. # Returns a reference to an array of keys and references to arrays. # Warning: If $hash{$n} contains $n then this expansion won't # terminate. sub expand { my ($key) = @_; my @result = ( $key ); # Keep the value. foreach my $subkey ( @{$hash{$key}} ) { # If it's a key, expand push @result, expand($subkey); # that too and append. } return \@result; } # Apply the algorithm to find the expanded "0" entry. $newhash{0} = expand(0) ; # Pretty print the result as a perl data structure. use Data::Dumper; print Dumper( $newhash{0} ); # Like the expand() routine, # but keep everything at the same depth. sub expandFlat { my ($key) = @_; my @result = ( $key ); foreach my $subkey ( @{$hash{$key}} ) { push @result, expandFlat($subkey); } return @result; } # Print out the flattened structure. print "(". join(",",expandFlat(0)) .")\n"; # Running this and compacting the Data::Dumper output a bit gives # # (1) # As a perl data structure: # $VAR1 = [ 0, [ '1', [ '3', [ '7' ], # [ '8' ] ], # [ '4' ] ], # [ '2', [ '5' ], # [ '6' ] ], # [ '15' ] ]; # # (2) # As a flat array # (0,1,3,7,8,4,2,5,6,15) # # which as I said, is pretty much your procedure # if not quite your outcome. #