Sort hash by value and key (in that order)

前端 未结 2 1356
广开言路
广开言路 2021-02-08 21:25

I\'m looking for a nice way to sort a hash in Perl by value first and by key afterwards.

Example:

 my %userids = (
  williams => \"Marketing\",
  smit         


        
2条回答
  •  礼貌的吻别
    2021-02-08 21:54

    I would like to add one more thing, use \L sequence in sorting.

    From Perlfaq4: How do I sort a hash (optionally by value instead of key)?

    To make our report order case-insensitive, we use the \L sequence in a double-quoted string to make everything lowercase. The sort() block then compares the lowercased values to determine in which order to put the keys.

    foreach (sort { $userids{$a} cmp $userids{$b} or "\L$a" cmp "\L$b" )  {
        print "$_: $userids{$_}\n"; 
    } 
    

    Output :

    brown: Marketing
    jones: Marketing
    williams: Marketing
    davis: Research
    Johnson: Research # here 'J'ohnson, J is in uppercase(taking assumption), come as fifth record
    smith: Research
    

    2.

    foreach (sort { $userids{$a} cmp $userids{$b} or $a cmp $b )  {
        print "$_: $userids{$_}\n"; 
    }
    

    Output:

    brown: Marketing
    jones: Marketing
    williams: Marketing
    Johnson: Research # here it shifted to fourth record
    davis: Research
    smith: Research
    

提交回复
热议问题