sorting strings numerically

0 views
Skip to first unread message

Benjamin Goldberg

unread,
Aug 18, 2002, 3:34:58 PM8/18/02
to
Michele Dondi wrote:
>
> I would like to sort strings alphabetically for what regards non digit
> chars and numerically for any block of digits. To make things clear,
> the following strings are sorted in the sense I want:
>
> abc90def07
> abc101def5
> abc101def06
> bbc999a
>
> Now:
>
> 1) Is there a ready made solution/package for a suitable comparison
> function to feed to "sort"?

Sort::Naturally

> 2) Also in case the answer to point 1 is affirmative, how would I go
> doing that myself? I have thought

I assume you mean, "in the case that there is no ready made solution,
how would I do it?"

Here's my solution:

my @sorted = map $$_[1], sort $$a[0] cmp $$b[0], map {
my @parts = split /(\d+)/;
for my $i ( 0 .. $#parts ) {
if( $i & 1 ) {
$parts[$_] = pack("N", $parts[$_]);
} else {
$parts[$_] = unpack("H*", $parts[$_]) . "\0";
}
}
[ join("", @parts), $_ ];
} @unsorted;

[untested]

--
tr/`4/ /d, print "@{[map --$| ? ucfirst lc : lc, split]},\n" for
pack 'u', pack 'H*', 'ab5cf4021bafd28972030972b00a218eb9720000';

Reply all
Reply to author
Forward
0 new messages