开发者

How can I loop through files in a directory in Perl? [duplicate]

This question already has answers here: Closed 12 years ago.

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 co开发者_运维问答ntained in the same directory. How would I do this in Perl?


#!/usr/bin/perl -w

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

Where

 @files = <*>;

can be

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

etc.


Enjoy.

opendir(DH, "directory");
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
}


You can use readdir or glob.

Or, you can use a module such as Path::Class:

Ordinarily children() will not include the self and parent entries . and .. (or their equivalents on non-Unix systems), because that's like I'm-my-own-grandpa business. If you do want all directory entries including these special ones, pass a true value for the all parameter:

@c = $dir->children(); # Just the children
@c = $dir->children(all => 1); # All entries

In addition, there's a no_hidden parameter that will exclude all normally "hidden" entries - on Unix this means excluding all entries that begin with a dot (.):

@c = $dir->children(no_hidden => 1); # Just normally-visible entries

Or, Path::Tiny:

@paths = path("/tmp")->children;
@paths = path("/tmp")->children( qr/\.txt$/ );

Returns a list of Path::Tiny objects for all files and directories within a directory. Excludes "." and ".." automatically.

If an optional qr// argument is provided, it only returns objects for child names that match the given regular expression. Only the base name is used for matching:

@paths = path("/tmp")->children( qr/^foo/ );
# matches children like the glob foo*

Getting the list of directory entries 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.

Path::Class is portable to operating systems other than *nix and Windows. On the other hand, AFAIK, its instances use more memory than do Path::Tiny instances.

If memory is an issue, you are better off using readdir in a while loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜