Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: No. files in folder

by broquaint (Abbot)
on Jun 23, 2005 at 10:44 UTC ( #469354=note: print w/ replies, xml ) Need Help??


in reply to No. files in folder

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;
HTH

_________
broquaint


Comment on Re: No. files in folder
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://469354]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (10)
As of 2014-08-20 21:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (124 votes), past polls