perl取得某目录下文件列表


You want a list of all the files, or all the files matching a certain pattern, or with a certain ending, in a directory.
你可以列出目录下的所有文件,或符合一定规则的。
Use opendir & readdir function--使用'opendir'和'readdir'函数
Reading directories is a bit like reading files. First you open the directory, then you read from it and then you close it. You use a directory handle much as you use a file handle.
Step 1: Opening the directory-打开目录句柄(像文件句柄)
To open the directory, we use a function called opendir. You use this much like the open function to open files. In the example below, we open the /tmp directory:
use strict;
use warnings;
my $directory = '/tmp';
opendir (DIR, $directory) or die $!;
Step 2: Reading the directory-读取目录
To read the files and directories in the directory we use the readdir function. readdir returns the name of each file or directory in the opened directory in turn when used in scalar context, or a list of the names of all files and directories in that directory when used in list context. This means that we can use readdir in a foreach loop (or any other loop construct):
while (my $file = readdir(DIR)) {
#next if ($file =~ m/^\./);#不显示出以'.'开头的文件
#next unless (-d "$dir/$file");#仅显示出目录
#next unless (-f "$dir/$file");#仅对文件进行处理
#next unless ($file =~ m/\.txt$/);#处理那些以'.txt'结尾的文件
print "$file\n";
}
将取得所有的文件及目录(默认情况下),包括'.'与'..',目录仅为其名字,并不会递归其下的目录内容。
Step 3: Closing the directory-关闭目录句柄
We use the function closedir to close the directory once we are finished with it. Like files, the directory will be closed when the program terminates, but sometimes you will need to explicitly close the directory:
closedir(DIR);
下面介绍一个高级示例
A more advanced example is to use grep to filter out the files you want. The following example (based on a code sample from perldoc -f readdir) gets all the files (not directories) beginning with a period from the open directory. The filenames are found in the array @dots.
my $dir = '/tmp';
opendir(DIR, $dir) or die $!;
my @dots
= grep {
/^\./ # Begins with a period
&& -f "$dir/$_" # and is a file
} readdir(DIR);
# Loop through the array printing out the filenames
foreach my $file (@dots) {
print "$file\n";
}
closedir(DIR);
File::Find--多用于递归列出,下将详细介绍。
You can use the File::Find module to recursively search through a directory (or directories). It is best used when you want to perform some operation on each file. See perldoc File::Find for more information.
---------------------------------------
use File::Find;
my $path="/home/hto/docs";
find(\&findme,$path);
sub findme{
my $dir=$File::Find::dir;
#跳过当前'.'文件
next if($_=~/^\./);
print "'$_' AT directory of ".$dir."\n";
}
Glob
Another way of getting a directory listing - if you're only interested in the current directory and not in any sub-directories - is to use glob. You can pass glob a pattern (or patterns) to match and it will return any files that match. The example below will list all .pl and .pm files in the current directory:
my @files=glob("$dir*");
#my @files = glob("*.pl *.pm");
foreach my $file (@files) {
print "$file\n";
}
See also
perldoc -f opendir
perldoc -f readdir
perldoc -f closedir
perldoc -f -X
perldoc -f grep
perldoc File::Find
perldoc -f glob
perldoc File::Glob
原文参考(笔者有改动)
one-line应用示例
列出当前目录
perl -le 'opendir(DIR,".");print for readdir(DIR);'
列出当前目录以'.'开头的文件
perl -le 'opendir(DIR,"."),@me=readdir(DIR);for(@me){print if /^\./ and -f}' -e 'END {close DIR}'
列出当前目录以'.pl'结尾的文件
perl -le 'print for glob("*.pl")'
递归列出目录下的文件及目录
----------------------
use File::Find qw(finddepth);
use Data::Dumper;
my $dir='';
my @files;
finddepth(sub {
return if($_ eq '.' || $_ eq '..');
push @files, $File::Find::name;
}, $dir);
print Dumper(@files);
----------------------
use File::Find qw(find);
use Data::Dumper;
my $dir='.';
sub list_dirs {
my @dirs = @_;
my @files;
find({ wanted => sub { push @files, $_ } , no_chdir => 1 }, @dirs);
return @files;
}
push @paths, list_dirs($dir);
print Dumper(@paths);
----------------------
use Data::Dumper ;
use File::Find::Rule ;
my $dir = shift ; # get directory from command line
my @files = File::Find::Rule->in( $dir );
print Dumper( \@files ) ;
----------------------
use Data::Dumper ;
use File::Find::Rule ;
my $dir = shift ;
my $level = shift // 2 ;
my @files = File::Find::Rule->file()
->name( "*.txt" )
->maxdepth( $level )
->in( $dir );
print Dumper( \@files ) ;
Or alternatively create an iterator :
my $ffr_obj = File::Find::Rule->file()
->name( "*.txt" )
->maxdepth( $level )
->start ( $dir );
while (my $file = $ffr_obj->match() ){
print "$file\n"
}
----------------------
当然也有更多的简单示例
chdir $dir or die "Cannot chroot to $dir: $!\n";
my @files = glob("*.txt");
Use Perl Globbing:
my $dir = </dir/path/*>
On Linux, I prefer find:
my @files = map { chomp; $_ } `find`;
----------------------
----------------------
----------------------
----------------------
更多示例待续.....
----------------------
你可以列出目录下的所有文件,或符合一定规则的。
Use opendir & readdir function--使用'opendir'和'readdir'函数
Reading directories is a bit like reading files. First you open the directory, then you read from it and then you close it. You use a directory handle much as you use a file handle.
Step 1: Opening the directory-打开目录句柄(像文件句柄)
To open the directory, we use a function called opendir. You use this much like the open function to open files. In the example below, we open the /tmp directory:
use strict;
use warnings;
my $directory = '/tmp';
opendir (DIR, $directory) or die $!;
Step 2: Reading the directory-读取目录
To read the files and directories in the directory we use the readdir function. readdir returns the name of each file or directory in the opened directory in turn when used in scalar context, or a list of the names of all files and directories in that directory when used in list context. This means that we can use readdir in a foreach loop (or any other loop construct):
while (my $file = readdir(DIR)) {
#next if ($file =~ m/^\./);#不显示出以'.'开头的文件
#next unless (-d "$dir/$file");#仅显示出目录
#next unless (-f "$dir/$file");#仅对文件进行处理
#next unless ($file =~ m/\.txt$/);#处理那些以'.txt'结尾的文件
print "$file\n";
}
将取得所有的文件及目录(默认情况下),包括'.'与'..',目录仅为其名字,并不会递归其下的目录内容。
Step 3: Closing the directory-关闭目录句柄
We use the function closedir to close the directory once we are finished with it. Like files, the directory will be closed when the program terminates, but sometimes you will need to explicitly close the directory:
closedir(DIR);
下面介绍一个高级示例
A more advanced example is to use grep to filter out the files you want. The following example (based on a code sample from perldoc -f readdir) gets all the files (not directories) beginning with a period from the open directory. The filenames are found in the array @dots.
my $dir = '/tmp';
opendir(DIR, $dir) or die $!;
my @dots
= grep {
/^\./ # Begins with a period
&& -f "$dir/$_" # and is a file
} readdir(DIR);
# Loop through the array printing out the filenames
foreach my $file (@dots) {
print "$file\n";
}
closedir(DIR);
File::Find--多用于递归列出,下将详细介绍。
You can use the File::Find module to recursively search through a directory (or directories). It is best used when you want to perform some operation on each file. See perldoc File::Find for more information.
---------------------------------------
use File::Find;
my $path="/home/hto/docs";
find(\&findme,$path);
sub findme{
my $dir=$File::Find::dir;
#跳过当前'.'文件
next if($_=~/^\./);
print "'$_' AT directory of ".$dir."\n";
}
Glob
Another way of getting a directory listing - if you're only interested in the current directory and not in any sub-directories - is to use glob. You can pass glob a pattern (or patterns) to match and it will return any files that match. The example below will list all .pl and .pm files in the current directory:
my @files=glob("$dir*");
#my @files = glob("*.pl *.pm");
foreach my $file (@files) {
print "$file\n";
}
See also
perldoc -f opendir
perldoc -f readdir
perldoc -f closedir
perldoc -f -X
perldoc -f grep
perldoc File::Find
perldoc -f glob
perldoc File::Glob
原文参考(笔者有改动)
one-line应用示例
列出当前目录
perl -le 'opendir(DIR,".");print for readdir(DIR);'
列出当前目录以'.'开头的文件
perl -le 'opendir(DIR,"."),@me=readdir(DIR);for(@me){print if /^\./ and -f}' -e 'END {close DIR}'
列出当前目录以'.pl'结尾的文件
perl -le 'print for glob("*.pl")'
递归列出目录下的文件及目录
----------------------
use File::Find qw(finddepth);
use Data::Dumper;
my $dir='';
my @files;
finddepth(sub {
return if($_ eq '.' || $_ eq '..');
push @files, $File::Find::name;
}, $dir);
print Dumper(@files);
----------------------
use File::Find qw(find);
use Data::Dumper;
my $dir='.';
sub list_dirs {
my @dirs = @_;
my @files;
find({ wanted => sub { push @files, $_ } , no_chdir => 1 }, @dirs);
return @files;
}
push @paths, list_dirs($dir);
print Dumper(@paths);
----------------------
use Data::Dumper ;
use File::Find::Rule ;
my $dir = shift ; # get directory from command line
my @files = File::Find::Rule->in( $dir );
print Dumper( \@files ) ;
----------------------
use Data::Dumper ;
use File::Find::Rule ;
my $dir = shift ;
my $level = shift // 2 ;
my @files = File::Find::Rule->file()
->name( "*.txt" )
->maxdepth( $level )
->in( $dir );
print Dumper( \@files ) ;
Or alternatively create an iterator :
my $ffr_obj = File::Find::Rule->file()
->name( "*.txt" )
->maxdepth( $level )
->start ( $dir );
while (my $file = $ffr_obj->match() ){
print "$file\n"
}
----------------------
当然也有更多的简单示例
chdir $dir or die "Cannot chroot to $dir: $!\n";
my @files = glob("*.txt");
Use Perl Globbing:
my $dir = </dir/path/*>
On Linux, I prefer find:
my @files = map { chomp; $_ } `find`;
----------------------
----------------------
----------------------
----------------------
更多示例待续.....
----------------------
该文章最后由 阿炯 于 2013-08-29 17:13:50 更新,目前是第 2 版。