2011-10-20 32 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 
     } 
    } 
}