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

I need to scan all directories and their subdirectories so that I can build up an array of directory names.

I've used File::Find to get an array of directory names for my root directory.

sub test { use File::Find; &find(\&wanted, 'E:/Common/Intranet/'); } sub wanted { if($File::Find::name !~ m/\./) { $dirlist[$count] = $File::Find::name; } $count++; }

I don't know how to get it to work recursively though.

Any help greatly appreciated.

Replies are listed 'Best First'.
Re: recursively scanning directories
by Beatnik (Parson) on Jun 19, 2001 at 12:12 UTC
    The POD for File::Find is pretty clear on the topic :) Normal behaviour is recursive...
    For example:
    #!/usr/bin/perl -w use strict; use File::Find; my @files = (); &find(\&wanted,'E:\Common\Intranet'); sub wanted { if (!/\./) { push(@files,$_); } } #if you actually wanna look for files with no period in it #Do something with @files
    Greetz
    Beatnik
    ... Quidquid perl dictum sit, altum viditur.
Re: recursively scanning directories
by grinder (Bishop) on Jun 19, 2001 at 12:30 UTC

    Some comments:

    • One usually pulls a use foo statement outside a subroutine.
    • You just want to say
      sub wanted { return if $_ eq '.' or $_ eq '..'; # matching /\./ might throw way too much push( @dirlist, $File::Find::name ) if -d $File::Find::name; # use push instead, # only if we are dealing with a directory }
    • The only reason why I can think that it would not recurse automatically would be if E: is a samba-mounted shared directory, in which case you have to futz around with $dont_use_nlink (some name like that, I forget, but it's in the documentation).

    --
    g r i n d e r
Re: recursively scanning directories
by stefan k (Curate) on Jun 19, 2001 at 12:36 UTC
    There exists a Module called File::Recurse, too. Unfortunately it's not in the 5.6 distribution so you need to get it from CPAN, but it maybe usefull for you.
    I read about it in Nate Patwardhan's Programming With Perl Modules (from O'Reilly)

    Regards... Stefan

Re: recursively scanning directories
by sierrathedog04 (Hermit) on Jun 19, 2001 at 13:56 UTC
    Sadmachine uses a normal regexp to match filenames:
    if($File::Find::name !~ m/\./)

    This condition is redundant. Every file by definition has a name, so every file matches the regexp.

    Update: Beatnik points out below that the regexp is not a redundancy, merely a mistake. It has the effect of not including all filenames with dots in them, e.g., myfile.txt and myscript.pl.

      Actually that's his attempt to match directories (which isn't ofcourse correct). That match will ignore all filenames with a dot in it.

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