How do I list the files in a directory?
原文地址:How do I list the files in a directory?
You want a list of all the files, or all the files matching a certain pattern, or with a certain ending, in a directory
The solution
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:
#!/usr/bin/perl
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)) {
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);
Directory Listing
Provided your program has sufficient access to the directory being read, readdir will list every file and directory contained in that directory. However, you often will not want all files or directories. For example, it is quite common to exclude all filenames beginning with a period:
#!/usr/bin/perl
use strict;
use warnings;
my $dir = '/tmp';
opendir(DIR, $dir) or die $!;
while (my $file = readdir(DIR)) {
# Use a regular expression to ignore files beginning with a period
next if ($file =~ m/^\./);
print "$file\n";
}
closedir(DIR);
exit 0;
See further down for a more compact way of doing this.
Find the directories
Sometimes you may want to find all the directories in a directory. Remember that readdir() gives you the names of the files and directories, not the paths. If you want to test a file using any of the standard file tests, you need to use the full path:
#!/usr/bin/perl
use strict;
use warnings;
my $dir = '/tmp';
opendir(DIR, $dir) or die $!;
while (my $file = readdir(DIR)) {
# A file test to check that it is a directory
# Use -f to test for a file
next unless (-d "$dir/$file");
print "$file\n";
}
closedir(DIR);
exit 0;
Find files ending in...
Quite often you want to find all files ending in a given suffix. For example, you may want to find all files ending in .txt:
#!/usr/bin/perl
use strict;
use warnings;
my $dir = '/tmp';
opendir(DIR, $dir) or die $!;
while (my $file = readdir(DIR)) {
# We only want files
next unless (-f "$dir/$file");
# Use a regular expression to find files ending in .txt
next unless ($file =~ m/\.txt$/);
print "$file\n";
}
closedir(DIR);
exit 0;
An advanced example
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.
#!/usr/bin/perl
use strict;
use warnings;
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);
exit 0;
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.
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:
#!/usr/bin/perl
use strict;
use warnings;
my @files = glob("*.pl *.pm");
foreach my $file (@files) {
print "$file\n";
}
exit 0;
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
How do I list the files in a directory?的更多相关文章
- 网站访问出现 ------ Can not write to cache files, please check directory ./cache/ .
最近在搞微商城时,突然出现了Can not write to cache files, please check directory ./cache/ .这样一个提示, 但最近好像没搞什么大动作,怎么 ...
- [Windows API] Listing the Files in a Directory,可用来数文件夹下有多少个子文件(夹)
转载 #include <windows.h> #include <tchar.h> #include <stdio.h> #include <strsafe ...
- Batch the files in the directory
#!/bin/bash #sourceFolder = /home/bigdatagfts/pl62716/refdata #targetFolder = /home/bigdatagfts/pl62 ...
- C# copy files from source directory to destination file and rename repeated files and does not override
static void CopyFiles() { string sourceDir = @"D:\C\ll"; string destDir = @"D:\LL&quo ...
- Common Linux log files name and usage--reference
reference:http://www.coolcoder.in/2013/12/common-linux-log-files-name-and-usage.html if you spend lo ...
- Files and Directories
Files and Directories Introduction In the previous chapter we coveredthe basic functions that pe ...
- Save results to different files when executing multi SQL statements in DB Query Analyzer 7.01
1 About DB Query Analyzer DB Query Analyzer is presented by Master Genfeng,Ma from Chinese Mainl ...
- How To Get Log, Trace Files In OA Framework Pages And Concurrent Request Programs
Goal Solution References APPLIES TO: Oracle Supplier Lifecycle Management - Version 12.1.2 and l ...
- EXTRACT FILES AND IMAGES FROM A SHAREPOINT CONTENT DATABASE
If you ever had the problem where you need to extract files from a SharePoint Content Database or no ...
随机推荐
- php设计模式 适配器模式
适配器模式,可以将截然不同的函数接口封装成统一的API: 应用举例,PHP的数据库操作有Mysql.Mysqli.pdo三种,可以用适配器模式统一成一致,类似的场景还有cache适配器,将memcac ...
- js location对象
location提供了与当前窗口中加载文档有关的信息.还提供了一些导航功能.它既是window对象的属性,又是document对象的属性,window.location与document.locati ...
- (视频) 《快速创建网站》2.1 在Azure上创建网站及网站运行机制
现在让我们开始一天的建站之旅. 本文是<快速创建网站>系列的第2篇,如果你还没有看过之前的内容,建议你点击以下目录中的章节先阅读其他内容再回到本文. 访问本系列目录,请点击:http:// ...
- Java中怎样创建线程安全的方法
面试问题: 下面的方法是否线程安全?怎样让它成为线程安全的方法? class MyCounter { private static int counter = 0; public static int ...
- git操作之常见问题解决方案
一.版本不一致 1. 错误信息: > git push -u origin master To ******.git ! [rejected] master -> master (non- ...
- 每日Scrum(9)
今天我们小组进行了软件的测试和界面的美化,特别是在主界面美化方面下了一些功夫,找了很多图片,把格式也处理的很完美,符合界面的一个框架,看起来,美观多了,至此,软件的beta版是基本完成了.
- ORACLE SQL Developer日期显示格式设置
ORACLE的SQL Developer工具默认的日期格式DD-MON-RR,在SQL查询中往往你看不到时间信息,此时你必须修改日期格式.具体如下所示 工具->首选项->数据库->N ...
- 0018 Java学习笔记-面向对象-类的基本要素
类与对象 大街上一个个的人,就是一个个对象 类是对一群对象的抽象,比如人都有性别.年龄.姓名,都会吃饭.睡觉等.姓名性别可以抽象为变量,吃饭睡觉可以抽象为方法,像下面一样定义个类来形容人 public ...
- 关于iOS构建版本提交iTunes后,一直不出现,没加号的解决方案
最近第一次遇到,正常打包,上传iTunes App Store,都能正常upload. 也可能是因为刚升了Xcode 8 的缘故,莫名其妙的小问题... 描述如下: 如果进iTunes的活动界面,也能 ...
- shutdown
关机命令 $sudo shutdowm [-hrc] -h定时关机,以分钟为单位的计时,时间或now -h now立即关机 -h +2020分钟后关机 -h 12:0012点关机 -r now立即重启 ...