I'd do this with glob, -M and sort:
$report = (sort{-M $a <=> -M $b}<*>)[0];
While this is short, sorting all files by date only to get at the newest one is a waste, specially for large directories. Also, it does a -M at each comparison in sort.

Using the Schwartzian Transform

$report = ( map { $_->[1] } sort { $a->[0] <=> $b->[0] } map { [-M $_, $_] } <*>)[0] );
eliminates multiple -M calls, but uses more memory, since we build an anonymous array for each file. It appears that this linear approach
$report = do { local *D; opendir(D,"."); my $t = time; my $ret; while(my $f = readdir(D)) { next if $f =~ /^\.\.?$/; my $ft = -M $f; if($ft < $t) { $ret = $f; $t = $ft; } } closedir(D); $ret; } ;
is a cheap way, and it's faster. benchmarking gives
Benchmark: timing 1000 iterations of do, golf, st... do: 8 wallclock secs ( 4.00 usr + 4.21 sys = 8.21 CPU) @ 12 +1.80/s (n=1000) golf: 74 wallclock secs (20.15 usr + 53.05 sys = 73.20 CPU) @ 13 +.66/s (n=1000) st: 34 wallclock secs (18.96 usr + 14.01 sys = 32.97 CPU) @ 30 +.33/s (n=1000) Rate golf st do golf 13.7/s -- -55% -89% st 30.3/s 122% -- -75% do 122/s 792% 302% --

running on my /usr/share/man/man1 directory. Note the big difference in CPU time. -M is 40% faster than (stat)[9], no wonder, it does look only at modification time and doesn't build a list. Benchmarking the call to ls in backticks doesn't make sense, because perl is blocked during the ls run.

--shmem

_($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                              /\_¯/(q    /
----------------------------  \__(m.====·.(_("always off the crowd"))."·
");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}

In reply to Re: grab newest file by shmem
in thread grab newest file by hasimir44

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.