nntp said:
I have an array of strings I need to sort from backward, such as in this
order.
cba
dba
eba
These seem sorted pretty normally to me. How is this backwards?
I shall assume for the remainder of the post that you mean you want a
sorted order along the lines of
abc bba cab ==> bba cab abc
ie, sorted by last character first, then second to last character, etc.
I perldoc -f sort, but I can not see it has this feature. Basically, if I
can reverse the string, sort them, then rever them back will do the trick.
The reverse function in perl only do on arrays not on strings.
What makes you believe that?
perldoc -f reverse
reverse LIST
In list context, returns a list value consisting of
the elements of LIST in the opposite order. In
scalar context, concatenates the elements of LIST
and returns a string value with all characters in
the opposite order.
$s = 'abc';
$r = reverse $s;
print "$r\n";
__END__
cba
You pass sort a function that defines how you want to sort the elements.
So you could simply do:
my @sorted = sort { (reverse $a) cmp (reverse $b) } @unsorted
However, you may also wish to consider using a Schwartzian Transform, to
minimize the performance hit of reversing every string every time the
sort subroutine is called:
my @sorted =
map $_->[0],
sort { $a->[1] cmp $b->[1] }
map [$_, scalar(reverse $_)],
@unsorted;
Paul Lalli