简体   繁体   English

Perl 排序 hash 并覆盖/添加到新变量

[英]Perl sort hash and overwrites/add to new variable

I'm quite new to perl and I need to find a way to sort hash.我对 perl 很陌生,我需要找到一种方法来对 hash 进行排序。 Many examples will run the sort then will just print to console.许多示例将运行排序,然后仅打印到控制台。 I need the new hash variable contain the key by sorted.我需要新的 hash 变量包含按排序的键。

For example:例如:

my %planets = (
  Mercury => 0.4,
  Venus   => 0.7,
  Earth   => 1,
);
 
foreach my $name (sort keys %planets) {
    printf "this $name \n";
}

I mean instead of printing I need to reference it back to another variable or even the %planets itself.我的意思是我需要将它引用回另一个变量甚至%planets本身,而不是打印。

So my expected final hash will be所以我预期的最终 hash 将是

%new_hash = (
    Earth => 1,
    Mercury => 0.4,
    Venus => 0.7
);

You can't.你不能。 There's no such thing as a sorted hash.没有排序的 hash 这样的东西。


Nothing says you have to iterate over the result of sort .没有什么说您必须遍历sort的结果。 You can store it in an array for later use.您可以将其存储在数组中以备后用。

my @sorted_keys = sort keys(%planets);

Another possibility is to convert the data structure you are using as you sort.另一种可能性是在排序时转换您正在使用的数据结构。

my @sorted_planets =
   map { [ $_, $planets{$_} ] }
      sort keys(%planets);

This produces:这会产生:

my @sorted_planets = (
   [ Earth   => 1   ],
   [ Mercury => 0.4 ],
   [ Venus   => 0.7 ],
);

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

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