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

Hellow monks,

I have the following data:

foo20021219_01.log foo20021220_01.log foo20021221_01.log foo20021218_01.log
The data is in an array.
What is the best way to sort my array based on the date stamp?
I.E.
foo20021218_01.log foo20021219_01.log foo20021220_01.log foo20021221_01.log
Thanks

Replies are listed 'Best First'.
Re: Sorting help
by pfaut (Priest) on Dec 31, 2002 at 14:41 UTC

    This just came up yesterday. See Sorting Files with Numbers.

    --- print map { my ($m)=1<<hex($_)&11?' ':''; $m.=substr('AHJPacehklnorstu',hex($_),1) } split //,'2fde0abe76c36c914586c';
Re: Sorting help
by gjb (Vicar) on Dec 31, 2002 at 15:08 UTC

    If the filenames are exactly the same form as you show them in the example, you don't even need to bother since a simple alphabetic sort (sort @array) will do the correct thing.

    Hope this helps, -gjb-

Re: Sorting help
by hardburn (Abbot) on Dec 31, 2002 at 15:09 UTC

    Use the sort function with a usersub call. The usersub can pull the numbers out of the name using a regex.

    The code below is untested, as always. There are probably more efficent ways of doing this, but this seems like the most straightforward way to me.

    sort { $a =~ /\A\w+(\d+)_(\d+).*\z/; my ($a1, $a2) = ($1, $2); $b =~ /\A\w+(\d+)_(\d+).*\z/; my ($b1, $b2) = ($1, $2); ($a1 <=> $b1) or ($a2 <=> $b2); }, @array;