in reply to Sorting question
What you may need here is a "Schwartzian Transform", so that you can sort based on a transformed key, where the transform is to expand any group of digits into a wider, fixed-sized group. In this way, "K-2-D-1A" gets a sort key of "K-002-D-001A", and "K-2-D-10A" gets a sort key of "K-002-D-010A". Since all sequences of numbers are now equally wide, you'll get the sort order you desire. But since the Schwartzian Transform holds on to unmodified data, you'll have the untransformed keys to display.
Here's an (untested) starting point:
This builds a composite data structure with the original key and a "normalized" key, sorts the structure based on the normalized key, and then discards the normalized key.my @data = qw(K-2-D-1A K-2-D-2A K-2-D-10A); my @sorted = map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { [$_, normalize_digits($_) ] } @data; sub normalize_digits { my ($key) = @_; $key =~ s/(\d+)/sprintf("%03d", $1)/eg; return $key; # thanks, ikegami }
Update: Or, better yet, don't reinvent the wheel, and use Sort::Naturally (which I'd somehow overlooked).
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Sorting question
by ikegami (Patriarch) on May 14, 2006 at 17:09 UTC | |
Re^2: Sorting question (slow)
by tye (Sage) on May 14, 2006 at 16:58 UTC | |
Re^2: Sorting question
by Scott7477 (Chaplain) on May 15, 2006 at 22:38 UTC |
In Section
Seekers of Perl Wisdom