perl嵌套哈希多种排序

Wak*_*nka 2 perl hashtable

我有这样的结构(散列哈希):

$VAR1 = {
          'Lee2000a' => {
                'abstract' => 'Abstract goes here',
                'author' => 'Lee, Wenke and Stolfo, Salvatore J'
                'title' => 'Data mining approaches for intrusion detection'
                'year' => '2000'
              },
          'Forrest1996' => {
                'abstract' => 'Abstract goes here',
                'author' => 'Forrest, Stephanie and Hofmeyr, Steven A. and Anil, Somayaji'
                'title' => 'Computer immunology'
                'year' => '1996'
                }
        };
Run Code Online (Sandbox Code Playgroud)

我想根据三个条件(按此顺序)对此结构进行排序:

第1个 - 按年份值(1996,2000)第2个 - 根据"外部"(Lee2000a,Forrest1996)结构键第3个 - 根据"内部"结构键(摘要,作者,标题,年份)按照alpahabetical顺序.

到目前为止,我有两个代码,我需要以某种方式结合:

I.代码符合第2和第3标准

for $i (sort keys(%bibliography)){
   print "$i => ", "\n";
   for $j (sort keys ($bibliography{"$i"})){
   print "\t $j -> ", $bibliography{"$i"}{"$j"},"\n";
   }
} 
Run Code Online (Sandbox Code Playgroud)

II.代码满足第一个条件

for $i (sort { ($bibliography{$a}->{year} || 0) <=> ($bibliography{$b}->{year} || 0) } keys %bibliography){
  print "$i => ", "\n";
  for $j (sort keys ($bibliography{"$i"})){
    print "\t $j -> ", $bibliography{"$i"}{"$j"},"\n";
  }
}
Run Code Online (Sandbox Code Playgroud)

非常感谢你

Mat*_*eck 8

要按某些次要条件排序,您可以使用逻辑OR:

my @sorted = sort {
                 $a{c1} <=> $b{c1} || 
                 $a{c2} <=> $b{c2}
             } @unsorted
Run Code Online (Sandbox Code Playgroud)

此示例将@unsorted按键对哈希值进行排序c1,然后,如果此比较相等,则按键c2.

为了您的目的,您可以通过这种方式组合外部循环的两个排序比较,以便您的排序块将读取:

(($bibliography{$a}->{year} || 0) <=> ($bibliography{$b}->{year} || 0)) ||
($a cmp $b)
Run Code Online (Sandbox Code Playgroud)