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

Hi Monks,

I am using the following lines to search for files in my C: drives. How can I modified my code to look anywhere except in "c:\winnt".

I know that the folder "winnt" is considered a directory in window.

finddepth (\&modified_file , c:\ ); sub modified_file { if (-f "$File::Find::name" ) { #do something } }

"$File::Find::name" is the current file.

--kirk

Edit Petruchio Wed Sep 4 04:12:19 UTC 2002 - Added markup

Replies are listed 'Best First'.
Re: How do you exclude certain folder or directories from a search
by rob_au (Abbot) on Sep 04, 2002 at 05:31 UTC
    Alternatively, using the File::Find::Rule interface ...

    use File::Find::Rule; my $rule = File::Find::Rule->new; $rule->any( $rule->new ->directory ->name('winnt') ->prune ->discard, $rule->new ); while ( my $file = $rule->match ) { .. }

    This module provides an alternate interface to the File::Find module and the code above works by creating a rule set ($rule->any) that matches all files ($rule->new) filtered by a second rule that trims the file path and discards any within the 'winnt' directory ($rule->new->directory->name('winnt')->prune->discard). All files located via this ruleset can then be iterated through within the $rule->match while-loop.

    A very nifty module ...

     

Re: How do you exclude certain folder or directories from a search
by grinder (Bishop) on Sep 04, 2002 at 07:44 UTC

    If you want to exclude a directory tree from a File::Find search, the best way is to prune the search space. This way you don't have to needlessly grovel through the directories and say "Should I do something here? Nope." The first time you encounter the directory you want to tell File::Find to short-circuit the search and go onto the next object in the filesystem. The following snippet should give you an idea about how to go about it:

    #! /usr/bin/perl -w use strict; use File::Find; my $ignore = 'winnt'; find( sub { if( -d $_ and m{$ignore$}o ) { $File::Find::prune = 1; return; } print "$File::Find::name\n" if -f _; }, shift || '.' );

    Tailor to suit your circumstances. You may have to worry about case-sensitivity of filenames (or not). You may also want to perform an exact match with eq instead of performing a regex match. You may want to exclude more than one directory.


    print@_{sort keys %_},$/if%_=split//,'= & *a?b:e\f/h^h!j+n,o@o;r$s-t%t#u'
      Just wanted to add my 1.3 cents. I agree, -prune should be the most effiecient method of skipping a directory.
Re: How do you exclude certain folder or directories from a search
by blaze (Friar) on Sep 04, 2002 at 02:51 UTC
    you could try something like
    sub modified_file{ if((-f "$File::Find::name") and ($File::Find::name ne "winnt")){ # do something } }
    This is so untested, but you get the picture
      blaze, thanks for responding --kirk
        Thanks grinder easy!