If you use the first version that Sudarshan posted, you might want to use
this instead.  It uses map, and is a lot faster.

my $latest = (sort {$b->{mtime} <=> $a->{mtime}}
             map {{mtime => -M $_, file => $_}}
             <$dir/*>)[-1];

print $latest->{file}, "\n";

Benchmark results with and without using map:

Benchmark: timing 100 iterations of No-MAP, With-MAP...
    No-MAP: 13 wallclock secs ( 2.43 usr  6.43 sys +  4.00 cusr  1.41 csys =
0.00 CPU)
  With-MAP:  8 wallclock secs ( 1.57 usr  0.81 sys +  4.04 cusr  1.27 csys =
0.00 CPU)

Using map allows -M to be performed on each file only once (instead of once
per sort iteration).  And since this is an expensive operation doing it only
once will save a lot of CPU time.

Rob


-----Original Message-----
From: Sudarshan Raghavan [mailto:[EMAIL PROTECTED]
Sent: Thursday, March 20, 2003 9:17 AM
To: Perl beginners
Subject: Re: Unix ls -lrt | tail -1 in Perl


On Thu, 20 Mar 2003, NYIMI Jose (BMB) wrote:

> Hello,
> 
> How can I do this unix command  in Perl ?  : ls -lrt | tail -1
> Actually, i would like to get the most recent file from a given directory.

my $latest = (sort {-M $b <=> -M $a} <$dir/*>)[-1];

or

my $latest;
while (<$dir/*>) {
    $latest = (defined ($latest) && (-M $_ > -M $latest)) ? $latest : $_;
}

Remember to check for the definedness of $latest if $dir is an empty 
directory

> 
> Thanks in advance for your input.
> 
> José.


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to