Perl通过哈希中的值对哈希进行排序 [英] Perl sorting hash by values in the hash

查看:132
本文介绍了Perl通过哈希中的值对哈希进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我有正确的想法,但有一些语法/约定的东西我搞乱了,因为我得到错误全局符号%timeHash需要明确的包名称。



$ p
$ b

  foreach $ key(sort hashValueDescendingNum(keys(%timeHash))){
print \t $ key \t\t $ timeHash {$ key} \\\
;
}



sub hashValueDescendingNum {
my $ hash = shift;
$ hash {$ b}< => $哈希{$ a}的;
}


解决方案

内联

  foreach my $ key(sort {$ timeHash {$ b}< => $ timeHash {$ a}} keys%timeHash){
打印\t $ key\t\t $ timeHash {$ key} \\\
;

使用自定义排序功能的方式不会奏效,因为那么你的子将需要访问原始散列。

  foreach my $ key(sort hashValueDescendingNum(keys(%timeHash)) ){
print\t $ key \t\t $ timeHash {$ key} \\\
;
}

sub hashValueDescendingNum {
$ timeHash {$ b}< => $ timeHash {$ a}的; #Ew。
}

相反,您可以进一步抽象:

  foreach my $ key(sortedHashKeysByValueDescending(%timeHash)){
print\ t $ key \t\t $ timeHash {$ key} \\\
;
}

sub sortedHashKeysByValueDescending {
my%hash = @_;
my @keys = sort {$ hash {$ b}< => $ hash {$ a}}键%hash;
返回@keys;
}

代码效率不高,因为它传递%hash,但引用会更好:

  foreach my $ key(sortedHashKeysByValueDescending(\%timeHash)){
print\t $ key\t\t $ timeHash {$ key} \\\
;
}

sub sortedHashKeysByValueDescending {
my $ hash = shift;
返回排序{$ hash-> {$ b}< => $ hash-> {$ a}}键%$ hash;
}


I think I have the right idea but there's some syntax/convention thing I'm messing up, because I get the error "Global symbol %timeHash requires explicit package name".

Code:

foreach $key (sort hashValueDescendingNum (keys(%timeHash))) {
   print "\t$key\t\t $timeHash{$key}\n";
}



sub hashValueDescendingNum {
   my $hash = shift;
   $hash{$b} <=> $hash{$a};
}

解决方案

Inline

foreach my $key (sort { $timeHash{$b} <=> $timeHash{$a} } keys %timeHash) {
   print "\t$key\t\t $timeHash{$key}\n";
}

Using a custom sort function the way you are trying to will not work well, because then your sub would need to access the original hash.

foreach my $key (sort hashValueDescendingNum (keys(%timeHash))) {
    print "\t$key\t\t $timeHash{$key}\n";
}

sub hashValueDescendingNum {
   $timeHash{$b} <=> $timeHash{$a}; # Ew.
}

Instead you can abstract it further:

foreach my $key (sortedHashKeysByValueDescending(%timeHash)) {
    print "\t$key\t\t $timeHash{$key}\n";
}

sub sortedHashKeysByValueDescending {
  my %hash = @_;
  my @keys = sort { $hash{$b} <=> $hash{$a} } keys %hash;
  return @keys;
}

The code is not efficient because it passes around the %hash though, references would be better:

foreach my $key (sortedHashKeysByValueDescending(\%timeHash)) {
    print "\t$key\t\t $timeHash{$key}\n";
}

sub sortedHashKeysByValueDescending {
  my $hash = shift;
  return sort { $hash->{$b} <=> $hash->{$a} } keys %$hash;
}

这篇关于Perl通过哈希中的值对哈希进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆