I copied this example from perldoc -f sort. I added the @old
array and the prints of the @new
arrays. Why do I get three different @new
arrays? Is there something wrong with my @old
?
@old = qw( =332 =43 =avxc =aed =jjj =3322 =aa44 =ssss );
say "\nold : @old\n";
# inefficiently sort by descending numeric compare using
# the first integer after the first = sign, or the
# whole record case-insensitively otherwise
@new = sort {
($b =~ /=(\d+)/)[0] <=> ($a =~ /=(\d+)/)[0]
||
uc($a) cmp uc($b)
} @old;
say "new_1: @new"; # =3322 =332 =43 =aa44 =aed =avxc =jjj =ssss
# same thing, but much more efficiently;
# we'll build auxiliary indices instead
# for speed
@nums = @caps = ();
for (@old) {
push @nums, /=(\d+)/;
push @caps, uc($_);
}
@new = @old[ sort {
$nums[$b] <=> $nums[$a]
||
$caps[$a] cmp $caps[$b]
} 0..$#old
];
say "new_2: @new"; # =avxc =332 =43 =3322 =aa44 =aed =jjj =ssss
# same thing, but without any temps
@new = map { $_->[0] }
sort { $b->[1] <=> $a->[1]
||
$a->[2] cmp $b->[2]
} map { [$_, /=(\d+)/, uc($_)] } @old;
say "new_3: @new\n"; # =3322 =332 =43 =avxc =aed =jjj =aa44 =ssss