package personel;
use warnings;
use strict;
sub sortAge { $b->[1] <=> $a->[1]; }
sub cmpAge1 { $main::b->[1] <=> $main::a->[1]; }
sub cmpAge2 { $::b ->[1] <=> $::a ->[1]; }
sub cmpAge3 { # slower
my $callingPkg = caller;
no strict 'refs';
${"$callingPkg\::b"}->[1] <=> ${"$callingPkg\::a"}->[1];
# ${"${callingPkg}::b"}->[1] <=> ${"${callingPkg}::a"}->[1]; # also works
}
return 1;
####
use warnings;
use strict;
use personel;
use Data::Dump;
my @personnel = (
[ 'amy', 35 ], [ 'bill', 55 ], [ 'george', 28 ], [ 'jason', 71 ],
);
print "doesn't work: \n";
my @not_sorted_by_age = sort personel::sortAge @personnel;
dd \@not_sorted_by_age;
print "\n";
print "does work: \n";
my @sorted_by_age_descending1 = sort personel::cmpAge1 @personnel;
dd \@sorted_by_age_descending1;
print "\n";
print "also works: \n";
my @sorted_by_age_descending2 = sort personel::cmpAge2 @personnel;
dd \@sorted_by_age_descending2;
print "\n";
print "also works (somewhat slower): \n";
my @sorted_by_age_descending3 = sort personel::cmpAge3 @personnel;
dd \@sorted_by_age_descending3;
print "\n";
print "original array (should be unchanged): \n";
dd \@personnel;
print "\n";
####
c:\@Work\Perl\monks\polmed>perl test.pl
doesn't work:
Use of uninitialized value in numeric comparison (<=>) at personel.pm line 7.
Use of uninitialized value in numeric comparison (<=>) at personel.pm line 7.
Use of uninitialized value in numeric comparison (<=>) at personel.pm line 7.
Use of uninitialized value in numeric comparison (<=>) at personel.pm line 7.
Use of uninitialized value in numeric comparison (<=>) at personel.pm line 7.
Use of uninitialized value in numeric comparison (<=>) at personel.pm line 7.
Use of uninitialized value in numeric comparison (<=>) at personel.pm line 7.
Use of uninitialized value in numeric comparison (<=>) at personel.pm line 7.
[["amy", 35], ["bill", 55], ["george", 28], ["jason", 71]]
does work:
[["jason", 71], ["bill", 55], ["amy", 35], ["george", 28]]
also works:
[["jason", 71], ["bill", 55], ["amy", 35], ["george", 28]]
also works (somewhat slower):
[["jason", 71], ["bill", 55], ["amy", 35], ["george", 28]]
original array (should be unchanged):
[["amy", 35], ["bill", 55], ["george", 28], ["jason", 71]]