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
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