Perl Programming Question:

Download Job Interview Questions and Answers PDF

How do I sort a hash by the hash key?

Perl Programming Interview Question
Perl Programming Interview Question

Answer:

Suppose we have a class of five students.
Their names are kim, al, rocky, chrisy, and jane.

Here's a test program that prints the contents
of the grades hash, sorted by student name:

#!/usr/bin/perl -w

%grades = (
kim => 96,
al => 63,
rocky => 87,
chrisy => 96,
jane => 79,
);

print "ntGRADES SORTED BY STUDENT NAME:n";
foreach $key (sort (keys(%grades))) {
print "tt$key tt$grades{$key}n";
}


The output of this program looks like this:


GRADES SORTED BY STUDENT NAME:
al 63
chrisy 96
jane 79
kim 96
rocky 87



}

Download Perl Programming Interview Questions And Answers PDF

Previous QuestionNext Question
How do I do < fill-in-the-blank > for each element in a hash?How do you print out the next line from a filehandle with all its bytes reversed?