How do I sort a hash by the hash value?
Submitted by: AdministratorHere's a program that prints the contents
of the grades hash, sorted numerically by the hash value:
#!/usr/bin/perl -w
# Help sort a hash by the hash 'value', not the 'key'.
to highest).
sub hashValueAscendingNum {
$grades{$a} <=> $grades{$b};
}
# Help sort a hash by the hash 'value', not the 'key'.
# Values are returned in descending numeric order
# (highest to lowest).
sub hashValueDescendingNum {
$grades{$b} <=> $grades{$a};
}
%grades = (
student1 => 90,
student2 => 75,
student3 => 96,
student4 => 55,
student5 => 76,
);
print "ntGRADES IN ASCENDING NUMERIC ORDER:n";
foreach $key (sort hashValueAscendingNum (keys(%grades))) {
print "tt$grades{$key} tt $keyn";
}
print "ntGRADES IN DESCENDING NUMERIC ORDER:n";
foreach $key (sort hashValueDescendingNum (keys(%grades))) {
print "tt$grades{$key} tt $keyn";
}
Submitted by: Administrator
of the grades hash, sorted numerically by the hash value:
#!/usr/bin/perl -w
# Help sort a hash by the hash 'value', not the 'key'.
to highest).
sub hashValueAscendingNum {
$grades{$a} <=> $grades{$b};
}
# Help sort a hash by the hash 'value', not the 'key'.
# Values are returned in descending numeric order
# (highest to lowest).
sub hashValueDescendingNum {
$grades{$b} <=> $grades{$a};
}
%grades = (
student1 => 90,
student2 => 75,
student3 => 96,
student4 => 55,
student5 => 76,
);
print "ntGRADES IN ASCENDING NUMERIC ORDER:n";
foreach $key (sort hashValueAscendingNum (keys(%grades))) {
print "tt$grades{$key} tt $keyn";
}
print "ntGRADES IN DESCENDING NUMERIC ORDER:n";
foreach $key (sort hashValueDescendingNum (keys(%grades))) {
print "tt$grades{$key} tt $keyn";
}
Submitted by: Administrator
Read Online Perl Programming Job Interview Questions And Answers
Top Perl Programming Questions
☺ | How do you give functions private variables that retain their values between calls? |
☺ | How many ways can we express string in Perl? |
☺ | How do you match one letter in the current locale? |
☺ | How do I set environment variables in Perl programs? |
☺ | How to open and read data files with Perl |
Top Coding/Programming Categories
☺ | Python Interview Questions. |
☺ | OOP Interview Questions. |
☺ | Software engineering Interview Questions. |
☺ | PHP Interview Questions. |
☺ | VBA (Visual Basic for Applications) Interview Questions. |