2012-07-31 109 views
2

這是我的問題: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://stackoverflow.com/questions/8671233/programatic-access-of-a-hash-element http://stackoverflow.com/questions/9789420/how-would-you -create-and-traverse-a-hash-of-depth-n-which-the-val http://stackoverflow.com/questions/10965006/convert-string-abc-to-hash-abc- in-perl – daxim 2012-07-31 12:29:13

回答

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

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

您可以使用循環。在每一步中,您都會深入到結構的一層。

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

您也可以使用Data::Diver

-1

您可以建立散列元素表達式並呼叫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

1

相同的邏輯,別人給什麼,但使用foreach

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