[英]how to read all file names from a given directory using perl?
friends i 've this code which read file name from a directory and print those names 朋友,我有这段代码,该代码从目录中读取文件名并打印这些名称
opendir DIR1, "defaults" or die "cannot open dir: $!";#open the given dir
my @default_files=readdir DIR1;
foreach my $fls(@default_files){
chomp($fls);
print "$fls\n";
}
when i run the above code i've got 当我运行上面的代码时
.
..
PGR.csv
report.csv
std_headers.csv
tab_name.txt
'm confused what is first two lines? 我很困惑前两行是什么? thanks in advance 提前致谢
A simpler alternative can be using the glob
function: 一个更简单的选择可以使用glob
函数:
my @default_files = glob 'defaults/*';
Or: 要么:
my @default_files = <defaults/*>;
These functions filter out file and directory entries that begin with .
这些函数会过滤出以开头的文件和目录条目.
, just like the shell does. ,就像shell一样。
The first to lines are: 第一行是:
.
link to the directory you are currently visiting. 链接到您当前正在访问的目录。
..
link to the directory above the directory (parent directory) you are visiting. ..
链接到您要访问的目录(父目录)上方的目录。
EDIT: 编辑:
One possibility to filter out both named entries would be using grep
: 过滤掉两个命名条目的一种可能性是使用grep
:
opendir DIR1, "tmp" or die "cannot open dir: $!";
my @default_files= grep { ! /^\.\.?$/ } readdir DIR1;
foreach my $fls (@default_files) {
chomp($fls);
print "$fls\n";
}
"." “。” means the present working directory and ".." means the parent directory of the present working directory 表示当前工作目录,“ ..”表示当前工作目录的父目录
In a directory listing, .
在目录列表中, .
stands for Working Directory and ..
stands for Parent Directory . 代表工作目录 , ..
代表父目录 。
In scalar context, you can skip those entries by explicitly checking for them: 在标量上下文中,可以通过显式检查它们来跳过这些条目:
while (defined(my $next = readdir $dir)) {
next if $next =~ /\A[.][.]?\z/;
# ...
}
or in list context: 或在列表上下文中:
my @entries = grep !/\A[.][.]?\z/, readdir $dir;
If I am already using File::Slurp , I prefer to just use the read_dir
function it provides. 如果我已经在使用File :: read_dir
,我更喜欢只使用它提供的read_dir
函数。 The following will automatically skip .
以下内容将自动跳过.
and ..
in addition to prepending the path to the directory to each returned entry: 和..
除了将目录路径添加到每个返回的条目之前:
my @paths = read_dir('/path/to/dir', prefix => 1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.