Dear monks, I just spent awhile formulating the following code. I'm quite sure that it can be improved on, and I'm interesting in knowing how. Here's the goal of the code:

I need to sort a list of directories, and select the second directory when sorted highest first. For example:
dir-100-1 dir-100-10 dir-100-2 dir-100-9 dir-100-99 dir-2-1 dir- +28-1 dir-29-1 dir-29-2 dir-30-1 dir-3-1
I want to sort them to
dir-100-99 dir-100-10 dir-100-9 dir-100-2 dir-100-1 dir-30-1 dir-29-2 dir-29-1 dir-28-1 dir-3-1 dir-2-1
And I would select the second entry, dir-100-10.

Here's my code

ls -d ./dir-* | xargs perl -e'print ((sort {$b->[0] <=> $a->[0] || $b- +>[1] <=> $a->[1] } map { m|/dir-(\d+)-(\d+)|; [$1,$2,$_] } @ARGV)[1]- +>[2])'

A quick summary: it extracts the two numbers, sorts them, and prints out the 2nd entry in the sorted array. Note that I want to print the entire path, which will be an absolute path, unlike my contrived example here. There will always be two numbers separated by a dash, and they should always be sorted as I am doing so (left number, right side as a tie breaker). I bet there is a much simpler way to do what I want. I am ultimately looking for readability, not compactness (but if people turn this into a golf challenge, I would probably learn things too :).

I don't need to use perl for this, but I could not make this work with the command line sort. If this can be done more easily with the shell, I would prefer to do so, but I need to stick to standard shell commands and flags (this will be used on systems without GNU commands).

Thanks in advance


In reply to Command line file sorting by swkronenfeld

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.