Here's how I would do it:
#!/usr/bin/perl use strict; use warnings; die "Usage: $0 directory_path\n" unless ( @ARGV == 1 and -d $ARGV[0] ) +; my $target_dir = shift; chdir $target_dir or die "chdir $target_dir: $!\n"; opendir( my $dir, "." ); my %files = map { $_ => -M } grep /\w/, readdir( $dir ); my @bacs = sort { $files{$a} <=> $files{$b} } grep /\.bac$/, keys %fil +es; @bacs or die "No *.bac file found in $target_dir - nothing to do\n"; my $latest_bac_age = $files{$bacs[0]}; ( my $latest_bac_id = $bacs[0] ) =~ s/^(\w+).*/$1/; warn "latest bac file in $target_dir is $bacs[0]\n"; for my $f ( keys %files ) { my $result = "kept"; if ( $files{$f} > $latest_bac_age and $f !~ /^$latest_bac_id/ and +-f $f ) { unlink $f and $result = "deleted"; } warn "$result $f\n"; }
You can skip the "warn" outputs if you like, but for this sort of thing, I think it's nice to keep a log of what actually happens on a given run.

Updated the script to include the two "… or die …" conditions -- I should have had those in there from the beginning. Also updated the logic in the for loop: added the "-f $f" condition to the "if" statement (no point trying to unlink sub-directories), and only report "deleted" if the deletion actually succeeds.


In reply to Re: removing files with perl based on age and name by graff
in thread removing files with perl based on age and name by Jocqui

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.