且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我怎样才能保持Perl中的排序的散列?

更新时间:2023-02-04 22:27:33

Perl的哈希值没有秩序。您必须将它们切换到阵列,或(当你需要遍历散列例如)在他们使用排序。

Perl hashes do not have order. You must either switch them to arrays, or sort them upon usage (e.g. when you need to iterate over that hash).

第一种解决方案可能看起来像:

The first solution could look like:

@aoh =(
 [{ 4 => 8 }
, { 5 => 9 },
, { 3 => 15 }
 ],

...

第二个解决方案是:

foreach $subhash (@aoh) {
   foreach $sorted_key (sort { $subhash->{$a} <=> $subhash->{$b} } keys %$subhash) {
      # Do something with $subhash->{$sorted_key};
   }
}