Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

How to create nesting hashes given the innermost value and an array of keys?

by EchoAngel (Pilgrim)
on Mar 03, 2005 at 16:33 UTC ( [id://436280]=perlquestion: print w/replies, xml ) Need Help??

EchoAngel has asked for the wisdom of the Perl Monks concerning the following question:

E.g. given the array @a = qw/foo bar burp/ and the value 1, create a hash like
%h = ( 'foo' => { 'bar' => { 'burp' => 1 } } );

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How to create nesting hashes given the innermost value and an array of keys?
by Roy Johnson (Monsignor) on Mar 31, 2005 at 01:25 UTC
Re: How to create nesting hashes given the innermost value and an array of keys?
by niggles (Initiate) on Aug 06, 2007 at 19:11 UTC
    Input in @a, output in $last[-1].
    use Data::Dumper; $Data::Dumper::Deepcopy = 1; my @a = qw/foo bar baz/; my @last = (1); push @last, { $_ => $last[-1] } foreach reverse @a; print Dumper( $last[-1] ); # result
    I use Data::Dumper just to print the output. It is not required to obtain the result. Output:
    $VAR1 = { 'foo' => { 'bar' => { 'baz' => 1 } } };
Re: How to Create Hash for a value using keys in an array?
by codeacrobat (Chaplain) on Mar 26, 2006 at 10:40 UTC
    Why do it so complicated?
    %hash = map{($_, $value)} @array;

    Originally posted as a Categorized Answer.

Re: How to create nesting hashes given the innermost value and an array of keys?
by EchoAngel (Pilgrim) on Mar 03, 2005 at 16:35 UTC
    This functiontakes elements in an array and builds them into keys for a hash:
    # Usage: UsesArrayElementsAsKeyElementsInHash( \%hash, $value, @array + ) use Carp; sub UsesArrayElementsAsKeyElementsInHash { my $hash = my $root = ( ref $_[0] ? shift : {} ); my $value = shift; my $last = pop; for my $key ( @_ ) { $hash = ( $hash->{$key} ||= {} ); ref $hash or croak "key = $key\n"; } $hash->{$last} = $value; return $root; }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2024-04-24 23:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found