in reply to Re: Re: A little fun with hashes
in thread A little fun with hashes
It sounds like you would like to do a recursive descent, expanding each index into itself as well as its values in the hash, if any. I'm not quite sure how you can do that and get exactly the string that you describe, but the following does something like what you describe.
#!/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. #
|
|---|