tags:

views:

57

answers:

1

I have an array and I am making a hash instance from it. For instance, if array is:

@folders=(temp,usr,bin);

then i want to fill in hash:

$the_path{$folders[0]}{$folders[1]}{$folders[2]}="somevalue";

But if the array is only:

@folders=(bin);

then i want the path to be:

$the_path{$folders[0]}="somevalue";

The problem is I dont know beforehand how long the array is gonna be, and I would really like to avoid making x if statements for that solution scales terribly.

How do I do this?

+5  A: 

First, that's not how you define an array in Perl. You probably want to say

my @folders = ( 'temp', 'usr', 'bin' );

There's an old trick for making nested hash keys from a list:

my %the_path;
my $tmp = \%the_path;
foreach my $item( @folders ) { 
    $tmp->{$item} = { };
    $tmp = $tmp->{$item};
}

This will result in a structure like the following:

$VAR1 = {
          'temp' => {
                      'usr' => {
                                 'bin' => {}
                               }
                    }
        };

If you want to replace the empty hashref at the bottom-most level with a string, you can keep track of a count variable inside the loop.

friedo
+1 for beating me to the same solution :)
Cfreak
As always, we already have CPAN modules for that. [Data::Diver](http://p3rl.org/Data::Diver) is my favourite.
daxim