Search code examples
perlperl-data-structures

Adressing a hash of hashes with an array


This is my problem:

I have a file-system like data-structure:

%fs = (
    "home" => {
        "test.file"  => { 
            type => "file",
            owner => 1000, 
            content => "Hello World!",
        },
    },
    "etc"  => { 
        "passwd"  => { 
            type => "file",
            owner => 0, 
            content => "testuser:testusershash",
            },
        "conf"  => { 
            "test.file"  => { 
                type => "file",
                owner => 1000, 
                content => "Hello World!",
            },
        },
    },
);

Now, to get the content of /etc/conf/test.file I need $fs{"etc"}{"conf"}{"test.file"}{"content"}, but my input is an array and looks like this: ("etc","conf","test.file").

So, because the length of the input is varied, I don't know how to access the values of the hash. Any ideas?


Solution

  • my @a = ("etc","conf","test.file");
    
    my $h = \%fs;
    while (my $v = shift @a) {
      $h = $h->{$v};
    }
    print $h->{type};