[英]Printing keys based on Hash values in Perl
我需要在散列中打印基于vales的键。 我写道,这是代码
foreach $value (values %hash)
{
print "$value\t$hash{$value}\n";
}
错误:我只能打印值,但不能打印键。
任何帮助将不胜感激。
谢谢
哈希设计为按键访问,而不是按值访问。 您需要遍历键列表,而不是值。
然后,您可以使用键来访问关联的值。
foreach my $key (keys %hash) {
my $value = $hash{$key};
say "$key = \t$value";
}
print "$_\t$hash{$_}\n" for keys %hash;
试试:
for my $key (keys %hash) {
print "$key\t$hash{$key}\n";
}
一内胆:
map { print "$_\t$hash{$_}\n" } keys %hash;
如果你想迭代键和值,我可能会使用while和each:
while (my ($key, $value) = each %hash) {
say "$key -> $value";
}
如果要按值访问它,请将哈希定义为
$x = { 'x1' => [ 'one','x1']}
foreach ( values %$x )
{
foreach $m1 (@$_) {
print "$m1\n";
}
}
请注意,您可以通过值数组的第二个成员从值获取键。
标题请求根据值打印密钥。
如果你的苛刻表中的键和值应该是一对一的
foreach $key (keys %hash)
{
$r_hash{$hash{$key}}=$key;
}
....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.