Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: No. files in folder

by blazar (Canon)
on Jun 23, 2005 at 10:16 UTC ( #469343=note: print w/replies, xml ) Need Help??


in reply to No. files in folder

That's fine. But it will only work your pwd is $dir. Otherwise you will have either to move there or prepend it to the filenames. Personally I think that while opendir is great and necessary in some circumstances, it is quite often abused where a simple glob (which does an opendir, and a readdir, and all the dirty jobs for you behind the scenes) would suffice.

Update: incidentally -0 == 0. Probably the code originally had the sort the other way round and [-1,-2] as subscript.

Replies are listed 'Best First'.
Re^2: No. files in folder
by gellyfish (Monsignor) on Jun 23, 2005 at 10:33 UTC

    Well it's not quite fine, on some OS there is a chance that one could find oneself attempting to delete the current directory and it's parent ('.' and '..'). I would suggest something like:

    opendir my $d, $dir; + my @f = sort { -M $b <=> -M $a } map { "$dir/$_" } grep !/^\.{1,2}$/,readdir $d; + unlink @f[-0,1] if @f > 20;
    The only problem using the conditional like that on the unlink line is that it makes it more difficult to test whether the unlink succeeded - I would expand it to a full if block.

    /J\

      Indeed, this is IMHO another good reason to use glob instead. I thought it is never supposed to return qw/. ../, or are there osen where it does?!? I mean glob '*' of course. One can trim it to {his,her} own needs anyway. And if really need be, than the cure would be (fundamentally) the same.

        No, glob can return . and .. and nothing in the documentation seems to promise otherwise (I searched glob, perlop, and File::Glob). However, glob("*") will not return any dot-files, including the directories, because it works similarly to shell wildcards. Here's an example of where it does, though:

        $ perl -le'$,=" ";print glob(".*")' . .. .bash_history .bash_profile # and so on

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (5)
As of 2021-04-15 23:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?