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

Hello Monks, I need to get a list of files in a directory and any sub directory into an array. Can anyone provide some suggestions on how to accomplish this?
  • Comment on Obtaining a list of files in a directory and subdirectory.

Replies are listed 'Best First'.
Re: Obtaining a list of files in a directory and subdirectory.
by toolic (Bishop) on Oct 16, 2009 at 14:24 UTC
    There are many ways. I prefer File::Find::Rule to recursively find files in a directory tree:
    use File::Find::Rule; my @files = File::Find::Rule->file()->in( $directory );
Re: Obtaining a list of files in a directory and subdirectory.
by kennethk (Abbot) on Oct 16, 2009 at 14:26 UTC
    The classic approach is using a typeglob (perldata) globbing (glob, I/O Operators), but a simpler approach would be using the combination of opendir, readdir, and closedir to get the contents of a directory. You could also determine which of those entries are directories using the -d file test.

    Update: Oops, thanks cdarke.

      Thanks guys. I think i will go with the file::find::rule. However, when i try and do a simple search on a directory, i get the follwoing error: Subroutine main::find redefined at C:/Perl/site/lib/File/Find/Rule.pm line 21. Any ideas. The code is pretty simple:
      my @files = File::Find::Rule->file()->in( "c:/" );
        That warning (not an error) is thrown when you overwrite an existing subroutine, in this case you have two subroutines in your main package called "find". The File::Find::Rule module exports a subroutine named "find", so I'm guessing you've defined one as well in your code.
Re: Obtaining a list of files in a directory and subdirectory.
by Khen1950fx (Canon) on Oct 16, 2009 at 21:26 UTC
    As an alternative, you could use ack. I used this:

    ack -f --sort-files /path/to/dir
      you need -a switch ack -a -f --sort-files /path/to/dir otherwise you only get perl files (-a switch also ignored git/cvs... files/dirs)

      Alternatively you can use findrule - command line wrapper to File::Find::Rule

      findrule /path/to/dir findrule /path/to/dir -file findrule /path/to/dir -directory
      $ findrule . -directory -name ( Mouse* ) MouseX-AttributeHelpers-0.04 MouseX-AttributeHelpers-0.04/blib/arch/auto/MouseX MouseX-AttributeHelpers-0.04/blib/lib/auto/MouseX MouseX-AttributeHelpers-0.04/blib/lib/MouseX MouseX-AttributeHelpers-0.04/inc/Mouse MouseX-AttributeHelpers-0.04/lib/MouseX $ findrule MouseX-AttributeHelpers-0.04 -file -name ( *PL ) MouseX-AttributeHelpers-0.04/Makefile.PL $ findrule . -file -name ( README ) -maxdepth 2 MooseX-CompileTime-Traits-0.092801/README MooseX-Getopt-0.23/README MooseX-Method-Signatures-0.27/README MouseX-AttributeHelpers-0.04/README
      and just pipe to sort find.... | sort