[Kc] sort by mod date

Garrett Goebel garrett at scriptpro.com
Mon Jun 14 08:44:52 CDT 2004


jyoung79 at kc dot rr dot com wrote:
> 
> I'm new to Perl and I was just curious if anyone here had
> any thoughts about the code below.  I'm running this on OS
> X (currently using an app called 'Affrus') and it sorts
> the files by modification date.  Here's my original code:
...
> 
> I asked this question also on the OS X Perl List and Jarkko
> had sent this:
> 
> -------
> opendir(DIR, shift || ".") && print map { "$_->[1]\n" }
> sort { $a->[0] <=> $b->[0] || $a->[1] cmp $b->[1] }
> map { [ (stat($_))[9], $_ ] } grep { !/^\.{1,2}$/ }
> readdir(DIR)
> -------
> 
> which I thought looked really cool, so I changed it a bit to:
> 
> -------
> opendir(DIR, shift || "/Users/jay/Desktop/Other Stuff/old stuff 4")
> && print map { "$_->[1]\n" } sort { $a->[0] <=> $b->[0] 
> || $a->[1] cmp $b->[1] } map { [ (stat($_))[9], $_ ] }
> grep { !/^\.{1,2}$/ } readdir(DIR)
> -------
> 
> but I never could make it work.  It kept giving me these errors:
> 
> *  Argument (file name) isn't numeric in numeric comparison (<=>)
> *  (62) Use of uninitialized value in string comparison (cmp)


The script works for me on a Win32 system. Did you cut and past from your
script or re-type it? 


The part which looked odd to me on my initial reading was:

> sort { $a->[0] <=> $b->[0] || $a->[1] cmp $b->[1] }

I haven't seen that before. But I guess I can see how it's useful in this
case. It basically means sort numerically by file modification time, sorting
further by filename where the modification times are equal.


You might see what the following produces:

opendir(DIR, shift || "/Users/jay/Desktop/Other Stuff/old stuff 4");
for my $i (grep { !/^\.{1,2}$/ } readdir(DIR)) {
  print '['. (stat($i))[9] . ", $i]\n"
}

That'll print out the contents of the list of anonymous array references
which are being sorted. For me it looked something like:

[1087217796, 1]
[1087217802, 2]
[1087217798, 3]
[1087217794, a]
[1087217800, b]
[1087217790, c]
[1087219921, kcpm.pl]

I don't imagine it'll look the same for you... or else you wouldn't be
getting that "isn't numeric" error when making a comparison like {$a->[0]
<=> $b->[0]} where for the first two elements in my example, the block
should reduce to {1087217796 <=> 1087217802}.

--
Garrett Goebel
IS Development Specialist

ScriptPro                   Direct: 913.403.5261
5828 Reeds Road               Main: 913.384.1008
Mission, KS 66202              Fax: 913.384.2180
www.scriptpro.com          garrett at scriptpro.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.pm.org/pipermail/kc/attachments/20040614/840bd501/attachment.htm


More information about the kc mailing list