Hi Monks,
I hope I won't commit any faux pas' on my first request for guidance!! But here goes...
I'm trying to order an array of records. The code runs but the array remains un-ordered. Am i missing something obvious? Here is my code (well not my code but adapted from an example here -> http://www.cs.pitt.edu/~ramirez/cs1520/perl/ex9.pl)
#!/usr/bin/perl -w # "-w" turns on all sorts of warnings about probabl
+e errors.
use diagnostics; # optional; causes warnings to be explained in grea
+ter detail.
use strict;
my @workers;
my $h = {name => "Herb", salary => 250000, job => "doctor"};
push(@workers, $h);
$h = {name => "Marge", salary => 400000, job => "ceo"};
push(@workers, $h);
$h = {name => "Ingmar", salary => 50000, job => "painter"};
push(@workers, $h);
print "\n Unsorted list\n";
show(@workers);
my @sort2 = sort by_sal @workers;
print "\n Sorted by salary\n";
show(@sort2);
sub by_sal
{
my %worka = %$a;
my %workb = %$b;
my $empa = $worka{"salary"};
my $empb = $workb{"salary"};
if ($empa < $empb) { return -1; }
elsif ($empa == $empb) { return 0; }
elsif ($empa > $empb) { return 1; }
}
sub show
{
foreach my $workref (@workers)
{
my %work = %$workref;
print "Name: ", $work{"name"}, "\t";
print "Salary: ", $work{"salary"}, "\t";
print "Job: ", $work{"job"}, "\n";
}
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.