2011-10-20 30 views
0

我正在創建散列哈希,並嘗試搜索或做模式匹配。如何搜索某些鍵的哈希散列?

散列

$hash{$var1}{$var2}{$var3}=$value; #where $var1 =1_1 : $var2 =2_1; $var3 =3,4; 

,我試着用鑰匙VAR3 這裏$ VAR4匹配可以更改值

for (sort keys %{$hash{'1'}{$var4}}) { # var4=2_1 : can also be 2_2 and so on 
    if ($_ =~ m/3,.*/) { # here 
     $new = $_;  # here new should get the value 3,4 
    } 
}  

我堅持的問題的模式是,除非我做以下

for (sort keys %{$hash{'1'}{'2'}}) 

我無法對鍵進行排序;總之不能用變量替換2。

+3

我不明白。對於初學者,你沒有提出任何問題。你指定了一些所需的輸出(「這裏新應該得到值3,4」),但你的代碼確實會給你那個輸出。 – ikegami

+0

您能向我們展示'%hash'轉儲的相關部分嗎? – Toto

回答

1

您是否嘗試過使用嵌套循環?你需要這樣的東西:在深入到訪問你需要的值之前,對$ var4鍵進行排序。

for my $var4 (sort keys %{$hash{'1'}}) { # var4=2_1 : can also be 2_2 and so on 
    # you can also filter the var4 keys here if you want 

    for my $var3 (keys %{$hash{1}{$_}}) { 
     if ($var3 =~ m/3,.*/) { # here 
      $new = $var3;  # here new should get the value 3,4 
     } 
    } 
}