Sorting an Array Numerically
Problem
You want to sort a list of numbers, but Perl’s
sort (by default) sorts alphabetically in ASCII
order.
Solution
Use Perl’s
sort function and
the <=> numerical comparison operator:
@sorted = sort { $a <=> $b } @unsorted;Discussion
The sort function takes an optional code block,
which lets you replace the default alphabetic comparison subroutine
with your own. This comparison function is called each time
sort has to compare two values. The values to
compare are loaded into the special package variables
$a and $b, which are
automatically localized.
The comparison function should return a negative number if
$a ought to appear before $b in
the output list, 0 if they’re the same and
their order doesn’t matter, or a positive number if
$a ought to appear after $b.
Perl has two operators that behave this way: <=> for sorting
numbers in ascending numeric order, and
cmp
for
sorting strings in ascending alphabetic order. By default,
sort uses cmp-style
comparisons.
Here’s code that sorts the list of PIDs in
@pids, lets the user select one, then sends it a
TERM signal followed by a KILL signal. We use a code block that
compares $a to $b with
<=> to sort numerically:
# @pids is an unsorted array of process IDs
foreach my $pid (sort { $a <=> $b } @pids) {
print "$pid\n";
}
print "Select a process ID to kill:\n";
chomp ($pid = <>);
die "Exiting ... \n" unless $pid && $pid =~ /^\d+$/;
kill('TERM',$pid);
sleep 2;
kill('KILL',$pid);If you use $a
<=>
$b or $a
cmp ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access