简体   繁体   English

根据Perl中的哈希值打印密钥

[英]Printing keys based on Hash values in Perl

I need to print keys based on vales in hash. 我需要在散列中打印基于vales的键。 Here is the code, I wrote 我写道,这是代码

foreach $value (values %hash)
{
    print "$value\t$hash{$value}\n";
}

Error: I can only print values, but not keys. 错误:我只能打印值,但不能打印键。

Any help will be greatly appreciated. 任何帮助将不胜感激。

Thanks 谢谢

Hashes are designed to be accessed by key, not by value. 哈希设计为按键访问,而不是按值访问。 You need to loop over a list of keys, not values. 您需要遍历键列表,而不是值。

Then you can use the keys to access the associated values. 然后,您可以使用键来访问关联的值。

foreach my $key (keys %hash) {
    my $value = $hash{$key};
    say "$key = \t$value";
}
print "$_\t$hash{$_}\n" for keys %hash;

Try with: 试试:

for my $key (keys %hash) {
    print "$key\t$hash{$key}\n";
}

一内胆:

map { print "$_\t$hash{$_}\n" } keys %hash;

I would probably use while and each if you want to iterate through keys and values: 如果你想迭代键和值,我可能会使用while和each:

while (my ($key, $value) = each %hash) {
    say "$key -> $value";
}

if you want to access it by values, then define your hash as 如果要按值访问它,请将哈希定义为

$x = {  'x1' => [ 'one','x1']}   


foreach ( values %$x ) 
{                                                                                     
     foreach $m1 (@$_) { 
        print "$m1\n";
     }
}     

Notice you can get the key from value by second member of the value array. 请注意,您可以通过值数组的第二个成员从值获取键。

The title requests to print key based on the value. 标题请求根据值打印密钥。

if your key and value in your harsh table should be one to one 如果你的苛刻表中的键和值应该是一对一的

foreach $key (keys %hash)
{
  $r_hash{$hash{$key}}=$key;
}
....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM