#!/usr/bin/perl use strict; use warnings; my @pair = ( [ qw(a b) ], [ qw(b a) ], [ qw(c b) ], [ qw(b c) ], ); my @triplet = ( [ qw(a b c) ], [ qw(b a c) ], [ qw(c b a) ], [ qw(b c a) ], ); print "Individual calls to mycmp()...\n"; foreach (@pair) { print "Same package: "; print $_->[0], ' ', $_->[1], ' => '; print $_->[0], ' ', $_->[1], "\n" if mycmp(@$_) == -1; print $_->[1], ' ', $_->[0], "\n" if mycmp(@$_) == 1; print $_->[1], ' ', $_->[0], "\n" if mycmp(@$_) == 0; print "Different package: "; print $_->[0], ' ', $_->[1], ' => '; print $_->[0], ' ', $_->[1], "\n" if Diffpackage::mycmp(@$_) == -1; print $_->[1], ' ', $_->[0], "\n" if Diffpackage::mycmp(@$_) == 1; print $_->[1], ' ', $_->[0], "\n" if Diffpackage::mycmp(@$_) == 0; } print "\nMultiple calls to mycmp() in sort...\n"; foreach (@triplet) { print "Same package: "; print $_->[0], ' ', $_->[1], ' ', $_->[2], ' => '; print (join ' ', sort { mycmp($a, $b) } @$_ ); print "\n"; print "Different package: "; print $_->[0], ' ', $_->[1], ' ', $_->[2], ' => '; print (join ' ', sort { Diffpackage::mycmp($a, $b) } @$_ ); print "\n\n"; } exit; sub mycmp { my ($first, $second) = @_; return 1 if $first ne ( mysort($first, $second) ); return -1 if $first eq ( mysort($second, $first) ); return 0; } sub mysort { my @ans = map { $_->[0] } sort { $a->[0] cmp $b->[0] } # $a and $b are always defined map { [ $_ ] } @_; return $ans[0]; } package Diffpackage; # this is the same as previous mycmp sub mycmp { my ($first, $second) = @_; return 1 if $first ne ( mysort($first, $second) ); return -1 if $first eq ( mysort($second, $first) ); return 0; } # this is the same as previous mysort sub mysort { my @ans = map { $_->[0] } sort { $a->[0] cmp $b->[0] } # this is where $a and $b can be undefined map { [ $_ ] } @_; return $ans[0]; } #### Individual calls to mycmp()... Same package: a b => a b Different package: a b => a b Same package: b a => a b Different package: b a => a b Same package: c b => b c Different package: c b => b c Same package: b c => b c Different package: b c => b c Multiple calls to mycmp() in sort... Same package: a b c => a b c Use of uninitialized value in string comparison (cmp) at ./testsort3.pl line 77. (Snip repeated error) Different package: a b c => a b c Same package: b a c => a b c Use of uninitialized value in string comparison (cmp) at ./testsort3.pl line 77. (Snip repeated error) Different package: b a c => a b c <== first two inputs sort correctly Same package: c b a => a b c Use of uninitialized value in string comparison (cmp) at ./testsort3.pl line 77. (Snip repeated error) Different package: c b a => b c a <== first two inputs sort correctly Same package: b c a => a b c Use of uninitialized value in string comparison (cmp) at ./testsort3.pl line 77. (Snip repeated error) Different package: b c a => b c a