I have a feeling this is either going to be easy or impossible.

I need to:
-read a dir
-find the ten newest files in it
-delete any others

I'm relatively sure that what I have below will remove anything older than 10 days, but I need to keep *10 days worth* of files. (Since this'll be run by cron daily, I have a problem on weekends or any other day when nothing is added to the directory..I fall below my mark of retaining the 10 *most recent* files.)

#!/usr/local/bin/perl -w use strict; use vars qw($archivedir @subdirs $subdirs); $archivedir = "/web/1/someplace" ; # READ CONTENTS OF DIRECTORY AND DELETE FILES OLDER THAN 10 DAYS opendir (ARCHDIR, "$archivedir") || die "Couldn't access the directory +!"; @subdirs = readdir(ARCHDIR); foreach $subdirs (@subdirs) { if (-M "$subdirs" > 10) { rmdir("$archivedir/$subdirs"); } } closedir ARCHDIR;

Ideas? Feel free to berate me if this turns out to be easy or my code looks silly. I'm still have tons to learn and welcome *any* advice.

Thanks!


In reply to find "x" quantity newest files in a dir by braintoast

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.