We help IT Professionals succeed at work.

Need to search for files in all subfolders

zzconsumer asked
Last Modified: 2008-03-17
I am totally new to PERL.
We are running a PERL/WIN32 on an IIS. I need a script to seach all subfolders for a specific file type.

This is a sample for searching one directory I found.
opendir(USERDIR, "$root_dir") || open_error("$root_dir");
@DIRS = readdir(USERDIR);

foreach $dir(sort(@DIRS)) {

$dir =~ s/^\.*//;

if (-d "$root_dir$dir") {  # test for files (no folders)

opendir(USERDIR, "$root_dir$dir");
@FILES = readdir(USERDIR);

foreach $file(sort(@FILES)) {

if ("$root_dir$file" =~ /htm/) {
$found_file = "$dir/$file";
$found_file =~ s/^\///;
print "$root_dir$found_file<BR>\n";

How must I change it?

Thanks in advance!
Watch Question


Adjusted points to 200

here is a smaller solution. it is based on the DOS dir command, so you dont have to worry about a lot of PERL code.

print "Usage: $0 file pattern.\n E.g. \t$0 c:\\*.pl \n\t$0 *.txt c:\windows\*.dll\n" if $#ARGV<0;

foreach $pattern (@ARGV){
  $ans=`dir /b/s $pattern`; ## Get the subdirectory listing for the pattern sepcified
  @ans=split(/\n/,$ans);  ##  Store each line as an element of an array
  print "Searching for $pattern\n\n";
        print $_,"\n";  ## Print every line of the array
  print "=================================================================\n";


Err... thanks a lot!
I don't understand anything of the script but it looks cool... ;)

I did not have a chance to get it to work. (I'm sure I'm too stupid for PERL. Or I just need some docs.)
The main thing is that I have a presentation tomorrow, and the script must run. Don't you see any chance just to change the existing script? The point is this is only a part of the script and I need to change some more subroutines. This may last too long if I need to know what I'm doing... ;)

ok here is what the script does.
Rather than reinventing the wheel and writing a code in PERL that would recursively goes thru the directories and searches for a file/file pattern, i am calling the DOS dir command from within PERL (dir /s/b file_pattern).

By saving on the recursive part of the program i can now concentrate on processing the incoming results. In the above script i am just storing them in an array and printing them one-by-one. You can choose to do anything that you want with these files by adding code after foreach(@ans){ .

ideally i would have preferred that you use the script i have provided, but i can understand your situation. i will look at the script today and try to come up with a solution, but i cant guarantee on the time :( due to my other professional commitments.

Hope that helps

Your initial script didnot traverse recursively. I put together a sub so we can do recursive call to it. I did it under Linux, you just need to change the / to \, I guess.
#! /usr/bin/perl -w
my $root_dir = "/home/zyu/.www";
my @files = ();
my @zeros = ();
my $found_file;
my $debug = 1;

@files = &AllFilesUnderAdir($root_dir, @zeros);

foreach $file (@files) {
    if ($file =~ /\.htm/) {
        $found_file = $file;
        $found_file =~ s/^\///;
        print "$found_file<BR>\n";
exit 0;

sub AllFilesUnderAdir() {
    my ($root, @list) = @_;
    my (@filesAtRoot, $dirEntry);
    opendir ROOTDIR, $root or ($debug and print STDERR "Err: Failed to open $root: $!" && return @list);
    @filesAtRoot = grep !/^\.\.?$/, readdir ROOTDIR;
    close ROOTDIR;
    foreach $dirEntry (@filesAtRoot) {
        if ( -f $dirEntry ) { push @list, $dirEntry}
        elsif ( -d $dirEntry ) { @list = &AllFilesUnderAdir($dirEntry, @list) }
        else { $debug and print "Donno what it is: $dirEntry. a symlink?\n"; }
    $debug and print "root=$root    files under it totals: ", $#list+1, "\n";
    return @list
This one is on us!
(Get your first solution completely free - no credit card required)

I forgot to mention that if you want to print the full pathname of the file it's in $File::Find::name (also see $File::Find::dir).


Thanks a lot to all of you! I had to decide which solution to use, used omere's, slightly changed.
However, my presentation was successful.

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.