Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
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 romping around the Monastery: (16)
As of 2015-07-02 17:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (44 votes), past polls