Sort hash by value and key (in that order)

前端 未结 2 1361
广开言路
广开言路 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 22:16

    Good reference: http://www.misc-perl-info.com/perl-sort.html#shv

    #!/usr/bin/perl
    
    my %userids = (
        williams => "Marketing",
        smith    => "Research",
        johnson  => "Research",
        jones    => "Marketing",
        brown    => "Marketing",
        davis    => "Research"
    );
    
    foreach (sort { ($userids{$a} cmp $userids{$b}) || ($a cmp $b) } keys %userids) 
    {
        print "$_: $userids{$_}\n";
    }
    

提交回复
热议问题