Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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:

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 }
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.

Update: Or, better yet, don't reinvent the wheel, and use Sort::Naturally (which I'd somehow overlooked).


In reply to Re: Sorting question by dws
in thread Sorting question by perl_seeker

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (6)
As of 2024-03-28 13:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found