http://qs321.pair.com?node_id=637213

swkronenfeld has asked for the wisdom of the Perl Monks concerning the following question:

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