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 ...
随机推荐
- json对象转为字符串,当做参数传递时加密解密
[son对象 字符串 互相转行] 比如我有两个变量,我要将a转换成字符串,将b转换成JSON对象: var a={"name":"tom","sex ...
- 组内Linq培训记录
注: 由于该培训是在组内分享,先写成了Word,而word中的代码都以截图方式呈现了,而在博客园不能很方便的粘贴截图进来,所以我用插入代码的方式加进来,如果文中说“如下图”或“如下图代码”,那么就直接 ...
- web项目修改名称问题
第一步:鼠标点击项目按F2 ,然后修改名称 第二步:备份web.xml 第三步:鼠标点击项目右键 选properties(一般位于最后面) 再在弹出框中输入WEB 第四步:将备份的web.xml文 ...
- Android简化xml sax解析
dom解析占用内存大(我这边需要解析各种各样的kml文件,有时4-5M的kml文件使用dom解析很多手机就内存溢出了),也需要引入第三方库,所以使用相对于节省内存很多.不需引入其他库的sax解析就是很 ...
- 单元测试中如何配置log4net
按道理来说,单元测试中基本没有对于日志的需求,这是由于单元测试的定位来决定的. 因为单元测试的思想就是针对的都是小段代码的测试,逻辑明确,如果测试运行不通过,简单调试一下,就能很容易地排查问题.但是单 ...
- phpStydy配置memcache扩展
一.下载并安装memcached服务器端软件 1.下载memcached软件 32位下载地址: memcached-win32-1.4.4-14.zip(直接下载),memcached-win3 ...
- oracle DB_LINK
1.先创建远程数据库服务名(注意,如果服务器既有oracle服务端又有客户端,需要在服务端的tnsnames.ora中配置服务名,否则会报如下错误): SQL> select count(*) ...
- DOS命令:IIS安装与卸载
//IIS7完全安装 start /w pkgmgr /iu:IIS-WebServerRole;IIS-WebServer;IIS-CommonHttpFeatures;IIS-StaticCont ...
- iOS 实现Tabbarcontroller中间自定义样式 最简单的方法
先上图: 如果我们要实现中间按钮自定义样式,方法应该蛮多,这里介绍一种最简单的. 1.创建类继承:UITabBarController,如下代码都是写在该类的 .m文件里 2.定义最中间的自定义样式, ...
- Bootstrap模态框(modal)垂直居中
http://v3.bootcss.com/ 自己也试了改了几种方式也不容乐观,发现在窗口弹出之前是获取不到$(this).height()的值,本想着是用($(window).height()-$( ...