Adressing哈希散列与数组

问题描述:

这是我的问题:Adressing哈希散列与数组

我有一个文件系统,如数据结构:

%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!", 
      }, 
     }, 
    }, 
); 

现在,得到的/etc/conf/test.file我需要$fs{"etc"}{"conf"}{"test.file"}{"content"}内容,但我的输入是一个数组,看起来像这样:("etc","conf","test.file")

所以,因为输入的长度是变化的,我不知道如何访问哈希的值。有任何想法吗?

+2

相关:http://*.com/questions/8671233/programatic-access-of-a-hash-element http://*.com/questions/9789420/how-would-you -create-and-traverse-a-hash-of-depth-n-which-the-val http://*.com/questions/10965006/convert-string-abc-to-hash-abc- in-perl – daxim 2012-07-31 12:29:13

my @a = ("etc","conf","test.file"); 

my $h = \%fs; 
while (my $v = shift @a) { 
    $h = $h->{$v}; 
} 
print $h->{type}; 

您可以使用循环。在每一步中,您都会深入到结构的一层。

my @path = qw/etc conf test.file/; 
my %result = %fs; 
while (@path) { 
    %result = %{ $result{shift @path} }; 
} 
print $result{content}; 

您也可以使用Data::Diver

您可以建立散列元素表达式并呼叫eval。这是整洁,如果它被包裹在一个子程序

my @path = qw/ etc conf test.file /; 

print hash_at(\%fs, \@path)->{content}, "\n"; 

sub hash_at { 
    my ($hash, $path) = @_; 
    $path = sprintf q($hash->{'%s'}), join q('}{'), @$path; 
    return eval $path; 
} 
+0

下来的选民请解释一下吗?只要字符串的来源是可靠的,只要'eval'没有问题。这里我们自己建造它,所以它是值得信赖的。 – Borodin 2012-07-31 12:37:44

相同的逻辑,别人给什么,但使用foreach

@keys = qw(etc conf test.file content); 
$r = \%fs ; 
$r = $r->{$_} foreach (@keys); 
print $r; 

$pname = '/etc/conf/test.file'; 
@names = split '/', $pname; 
$fh = \%fs; 
for (@names) { 
    $fh = $fh->{"$_"} if $_; 
} 
print $fh->{'content'}; 

路径::类接受一个数组。它还为您提供了一个辅助方法的对象,并处理跨平台斜线问题。

https://metacpan.org/module/Path::Class