Sunday, January 2, 2011

Sorting Country Codes Numerically Using a Custom Subroutine in Perl

$a and $b are compared, and the result is:
  • 1 if $a is greater than $b
  • -1 if $b is greater than $a
  • 0 if $a and $b are equal

Ex:
use strict;
use warnings;

my %countries = (
    '976' => 'Mongolia',
    '52'  => 'Mexico',
    '212' => 'Morocco',
    '64'  => 'New Zealand',
    '33'  => 'France'
);

foreach my $code (sort supersort keys %countries) {
    print "$code $countries{$code}\n";
}

sub supersort {
    if ($a > $b) {
        return 1;
    } elsif ($a < $b) {
        return -1;
    } else {
        return 0;
    }
}

No comments: