Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Re: Re: A little fun with hashes

by barrachois (Pilgrim)
on Aug 16, 2002 at 19:03 UTC ( #190730=note: print w/ replies, xml ) Need Help??


in reply to Re: Re: A little fun with hashes
in thread A little fun with hashes

As chromatic said, your initial assignments don't quite work. You cannot put an array ("3","4) into a scalar $hash{"1"}; instead, you need to use references.

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. #


Comment on Re: Re: Re: A little fun with hashes
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://190730]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (7)
As of 2014-07-28 08:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (193 votes), past polls