in reply to Re: (jeffa) Re: Substring Sort
in thread Substring Sort

Careful there... When you use the default sort and have extra data appended to each string, you have to make sure the extra data doesn't affect the sort order.

In this case, '|' (ASCII value 124) sorts after most other characters, so that code would sort a string before its prefixes. For example, 'string|extra data' comes after 'string plus|extra data', even though 'string' comes before 'string plus'.

I think the easiest way to solve this problem is by sticking a null character between the sort string and the extra data. (If the data contains null characters already, it takes a bit more work.)

@origarray = qw/ third|:|bb second|:|b fourth|:|c first|:|a /; my @sorted = map { /\0(.*)/s } sort map { (split /\|:\|/)[-1] . "\0$_" } @origarray; print "@sorted\n";
That outer map could be done with substr() and index() instead of a regex.