Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
Since it's my code I guess I ought comment on it:
opendir my $d, $dir;
This should really have an or die for sanity and a more descriptive variable name than $d such as $dir_handle.
my @f = sort { -M $b <=> -M $a } readdir $d;
This sorts all the files in the directory by modification time in reverse chronological order, again, a more descriptive variable like @file_list would be better suited. It should also only grab files so a grep should be added i.e
my @file_list = sort { -M $b <=> -M $a } grep -f, readdir $dir_handle;
And finally:
unlink @f[-0,1] if @f > 20;
This removes the two oldest files if there are more than 20 elements in @f. This code is somewhat broken as the pathnames are not fully qualified, which could be done like so:
use File::Spec 'catfile'; unlink map catfile($dir, $_), @f[0,1] if @file_list > 20;
Also the negated zero in the original code was just a blip from knocking out a quick bit of code in the CB. So, in summary, this more thought out code would be better:
use File::Spec 'catfile'; opendir my $dir_handle, $dir or die "Couldn't open '$dir': $!"; my @file_list = sort { -M $b <=> -M $a } grep -f, readdir $dir_handle; unlink map catfile($dir, $_), @f[0,1] if @file_list > 20;


In reply to Re: No. files in folder by broquaint
in thread No. files in folder by Win

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, 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, 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.
  • Log In?

    What's my password?
    Create A New User
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others musing on the Monastery: (5)
    As of 2021-04-14 10:17 GMT
    Find Nodes?
      Voting Booth?

      No recent polls found