tags:

views:

255

answers:

3

Possible Duplicate:
How can I list all of the files in a directory with Perl?

I want to loop through a few hundred files that are all contained in the same directory. How would I do this in Perl?

+5  A: 

You can use readdir or glob or my favorite File::Slurp::read_dir to get the list of files:

use File::Slurp;

my @files = read_dir '/path/to/directory';

for my $file ( @files ) {

}

Getting the list of files into an array wastes some memory (as opposed to getting one file name at a time), but with only a few hundred files, this is unlikely to be an issue.

Sinan Ünür
+2  A: 
#!/usr/bin/perl -w

@files = <*>;
foreach $file (@files) {
  print $file . "\n";
}

Where

 @files = <*>;

can be

 @files = </var/www/htdocs/*>;
 @files = </var/www/htdocs/*.html>;

etc.

EToreo
+1  A: 

Enjoy.

opendir("directory", DH);
my @files = readdir(DH);
closedir(DH);

foreach my $file (@files)
{
    # skip . and ..
    next if($file =~ /^\.$/);
    next if($file =~ /^\.\.$);

    # $file is the file used on this iteration of the loop
}
skarface