2

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?

1
  • 1
    You've got use strict; use warnings; at the top of your file, right? That will catch many errors for you. Commented Jul 23, 2010 at 14:45

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

As always, we already have CPAN modules for that. Data::Diver is my favourite.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.