简体   繁体   English

打印按值排序的Perl哈希键和值

[英]Printing perl hash keys and values sorted by value

I have ordered my hashmap by value and am printing them. 我已经按value对我的hashmap了排序并正在打印它们。 After printing the value, I would like to print the corresponding key . 打印值之后,我想打印相应的key

My code is currently: 我的代码当前为:

foreach my $value (sort (values %student_id_name_hash)){
   print "$value\n";
   // Print correspnding key here
}

I am trying to print unique student IDs (keys) and corresponding student names (values) , which may not be unique. 我正在尝试打印唯一的学生ID (keys)和相应的学生姓名(values) ,这些名称可能不是唯一的。

A method was suggested here that involved reverse but depends on the values being unique: http://www.perlmonks.org/?node_id=177969 在此建议了一种方法,该方法涉及reverse但取决于唯一的值: http : //www.perlmonks.org/?node_id=177969

Is this the best way to go about it? 这是最好的方法吗? There is no guarantee that the values will be unique in my case. 在我的情况下,不能保证这些值是唯一的。

If you want the keys as well as values, then you need to iterate based off of the keys and sort based off the value, like so: 如果需要键和值,则需要基于键进行迭代并根据值进行排序,如下所示:

for my $key ( sort { $student_id_name_hash{$a} cmp $student_id_name_hash{$b} }
    keys %student_id_name_hash )
{
    print "$key - $student_id_name_hash{$key}\n";
}

You can sort keys based on values associated with them 您可以根据与键关联的值对键进行排序

# standard good practice pragmas
use strict; use warnings; use utf8;

# sample/test data
my %id_hash = (
  X1 => 'Smith, Jane',
  Z9 => 'Doe, John',
);

# sort keys based on value and print
foreach my $key (sort {$id_hash{$a} cmp $id_hash{$b}} keys %id_hash ){
  my $value = $id_hash{$key};
  print "$value\n  $key\n";
}

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

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