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

Hello monks, I got an array with the following values. @asdf = {A,B,C,D,E,F, ...} I want to create a Hash with the structure $hash{A}{B}{C}{D}{E}{F}... I would have to do this many times for different array lengths into the same hash. How can I do this?

Replies are listed 'Best First'.
Re: How to Create Hash From this Array
by friedo (Prior) on Aug 14, 2006 at 15:55 UTC
    Assuming you mean you've got an array like @asdf = ('A', 'B', 'C', 'D', 'E', 'F'), you can create the hash like this:

    use Data::Dumper; my @asdf = (qw/A B C D E F/); my %hash; my $hr = \%hash; for(@asdf) { $hr->{$_} = { }; $hr = $hr->{$_}; } print Dumper \%hash;

    That prints:

    $VAR1 = { 'A' => { 'B' => { 'C' => { 'D' => { 'E' => { 'F' => {} } } } } } };
Re: How to Create Hash From this Array
by tinita (Parson) on Aug 14, 2006 at 16:01 UTC
    easy if the hash doesn't exist before:
    my $hash; $hash = { $_ => $hash } for reverse @array;
    if you don't want to overwrite old values in the hash, it's a bit more complicated, but not much.
    my $ref = \$hash; $ref = \$$ref->{$_} for @b;
Re: How to Create Hash From this Array
by davido (Cardinal) on Aug 14, 2006 at 16:03 UTC

    I want some clarification. Are you trying to create a hash with the keys of "A, B, C, D, E, and F", or are you trying to create a multi-dimensional datastructure, a hash of hashes of hashes of hashes (and so on)?

    Here are a couple examples of "how to do it", depending on what it actually is:

    # Create a hash with keys from @asdf my %hash; @hash{ @asdf } = (); # Use a hash slice. # Create a multidimensional datastructure: my $href; foreach my $key ( reverse @asdf ) { $href = { $key => $href }; }

    The latter approach creates a datastructure referenced by $href. It's built "in reverse" just to simplify the algorithm.


    Dave

Re: How to Create Hash From this Array
by ikegami (Patriarch) on Aug 14, 2006 at 16:37 UTC

    You can use tye's Data::Diver:

    use Data::Diver qw( DiveVal ); my %hash; my @keys = qw( A B C D E F ... ); DiveVal(\%hash, @keys);

    Caveat: It won't work if one of the keys looks like a number.

    Tested.

Re: How to Create Hash From this Array
by jdporter (Paladin) on Aug 14, 2006 at 16:11 UTC
Re: How to Create Hash From this Array
by planetscape (Chancellor) on Aug 15, 2006 at 20:18 UTC