2015-06-06 27 views
-1

我想只打印特定键:从以下散列对在Perl:访问特定的键值对的哈希

1: one 
2: two 
3: three 

,我使用下面的语句来打印我的哈希:

foreach (sort keys %hash) { 
    print "$_ : $hash{$_}"; 
} 

如果我只想从散列中打印1: one2: two,代码应该如何。

+4

怎么样'打印“1:$ hash {1}”;' –

回答

-1
foreach (sort keys %hash) { 
    if ($_ eq 1) { 
    print "$_ : $hash{$_}"; 
    last; 
    } 
} 

使用last会导致你的循环尽快满足条件退出。我希望这会解决你的问题。

+0

谢谢!解决方案为我工作! yay – Pankaj

+0

欢迎继续学习:) – shivams

+2

这是***错误***。没有必要搜索所有的散列键来查找匹配项:只是'print'1:$ hash {1}“'将会很好。 *所有*散列键都是字符串,应该*总是*使用'eq'进行比较 – Borodin

2

散列旨在为给定键快速查找值。如果您想要查看或针对每一个值进行操作,您只需通过所有密钥的foreach即可。如果你想只是仰望值对于给定的键,你会,由Сухой27Borodin提到,使用

use strict; 
use warnings; 

my %hash = (
    1 => "one", 
    2 => "two", 
    3 => "three", 
); 

print "1: $hash{1}\n"; 
print "2: $hash{2}\n"; 

,或者更一般的一键$key

print "$key: $hash{$key}\n";