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

How would I go about searching an inputted folder location (Ie. /home/username/me/cgi-bin/files ) for specific files with a given extension? Say I wanted to find the names of all .exe, .wav and .swf. I don't just need the filename, I need to apply something to each filename so I have to do it in a foreach.

I read up on readdir by previous posts on searching folders for files, but I'm not quite sure if that's the easiest way to do it or if it'll actually do what I'm looking for.

Replies are listed 'Best First'.
Re: searching folder for specific files
by broquaint (Abbot) on Feb 23, 2004 at 14:31 UTC
    For finding files in a given directory (or set of directories) it's a good idea to use one of the File::Find modules such as File::Find::Rule or File::Finder e.g
    use File::Find::Rule; my($ext, $dir) = qw( .{ext,wav,swf} /home/user/files ); for(find(file => name => $ext, in => $dir)) { ## operate on file here }
    HTH

    _________
    broquaint

Re: searching folder for specific files
by hanenkamp (Pilgrim) on Feb 23, 2004 at 14:32 UTC
    There are actually several ways of doing this. You should look for documentation on glob for one:
    do_something($_) foreach (<*.swf>);
    You can use opendir, readdir, and closedir and use a regexp or other file-test operation against each file found to determine if it matches your criteria:
    opendir FOO, $dir or die $@; foreach (readdir FOO) { do_something($_) if /\.swf$/; } closedir FOO;
    Or, if you need to recurse into subdirectories, you should consider File::Find. I'll let the documentation at CPAN illuminate that one for you.
Re: searching folder for specific files
by ambrus (Abbot) on Feb 23, 2004 at 14:29 UTC

    Readdir is what you want, unless you want to search for the files recursively (in subdirectories too). You must match the resulting filenames to a regexp like /\.exe\z/. Just don't forget to escape the dot!

Re: searching folder for specific files
by halley (Prior) on Feb 23, 2004 at 14:36 UTC
    I've never been a fan of readdir, when simpler list functions will do the same thing for you. If you had a single directory with 100_000 filenames in it, I might be inclined to believe that the readdir approach would be more appropriate.
    my $path = '/home/username/me/cgi-bin/files'; my @files = grep { -f and m/\.(exe|wav|swf)$/i } glob("$path/*");

    --
    [ e d @ h a l l e y . c c ]

Re: searching folder for specific files
by ambrus (Abbot) on Feb 23, 2004 at 14:55 UTC

    You say that using a glob or Find::File is simpler. I object this, as the code with readmore is simple enough:

    { opendir my $dir, "." or die; @l= grep /\.tbz\z/, readdir $dir; }; print $_, $/ for @l;