Sunday, January 2, 2011

Perl: Sort

$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:
%countries=('976','Mongolia','52','Mexico','212', 
'Morocco','64','New Zealand','33','France');
 
foreach (sort supersort keys %countries) {
        print "$_ $countries{$_}\n";
}

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

No comments: