Necos has asked for the wisdom of the Perl Monks concerning the following question:

Now, I know this question is kind of taken care of in the Q&A section (which is where I got the idea). However, I wanted to take the recursive listing of directories a little further, and look at using opendir, readdir, and for / map to find and delete contraband (e.g., .mp3 and .exe).

Of course, we all know that filename extensions can be changed, but that's not important as getting the basics down (for example, checking the last 128 bytes in a file for ID3 tags can help to identify an mp3). Here is my codebase (which needs some advising):
#!/usr/bin/perl -w recurse('c:'); #testing this on a windows machine sub recurse { my $dir = shift; #print $dir,$/; opendir(R,$dir) || die $!; my @dives = grep { $_ ne '.' && $_ ne '..' && -d $_ } readdir(R); +#build a list all of the directories @dives = map { join('/',$dir,$_) } @dives; print "$_\n" for @dives; my @contra_band = ('avi','mp3','mp2','mpeg'); my @found; foreach my $a (@contra_band) { my @del = grep { $_ =~ /\Q$a\E$/ } readdir(R); #look for the f +ile extensions map { push(@found,$_) } @del; #create an array of things to un +link later print @del; } map { recurse($_) } @dives; #couldn't think of a for loop to do the + same thing... I don't know what is wrong with me today. }
The only problem with this code, is that it only seems to work on some directories and not others... Any further guidance is appreciated.

Theodore Charles III
Network Administrator
Los Angeles Senior High
4650 W. Olympic Blvd.
Los Angeles, CA 90019
323-937-3210 ext. 224
email->secon_kun@hotmail.com
perl -e "map{print++$_}split//,Mdbnr;"

Replies are listed 'Best First'.
(jeffa) Re: Recursing subdirectories for contraband...
by jeffa (Bishop) on Jun 10, 2002 at 18:30 UTC
    Use File::Find -
    use strict; use File::Find; @ARGV = '.' unless @ARGV; find sub { return if -d; unlink $_ if /\.avi$/ or /\.mp3$/ or /\.mp2$/ or /\.mpeg$/; }, @ARGV;

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: Recursing subdirectories for contraband...
by Beatnik (Parson) on Jun 10, 2002 at 18:29 UTC
    You can use File::Find...
    #!/usr/bin/perl use File::Find; sub do_something { print $File::Find::name,"\n" } } find( {wanted=>\&do_something, #Call this subroutine follow=>1}, "/path/stuff"); #Edit path here
    IIRC, there has been a thread on this numerous times before...
    Update: A long, long time ago, in a galaxy far away... uhm wait, other story :) anyway, Recursion example (Directory sizing on the side)

    Greetz
    Beatnik
    ... Quidquid perl dictum sit, altum viditur.