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 ...
随机推荐
- linux下安装jdk+tomcat+eclipse+mysql
我的环境:主机是win7的,虚拟机是VWare Workstation 6.0 ,linux系统为Red Hat Enterprise Linux 5 64位 各软件版本:jdk是jdk-6u ...
- Java是如何处理别名(aliasing)的
什么是Java别名(aliasing) 别名意味着有多个别名指向同一个位置,且这些别名有不同的类型. 在下面的代码例子中,a和b是两个不同的名字,有不同的类型A和B,B继承A B[] b = new ...
- java 某字符串在另一字符串中是否存在
boolean a = 字符串a.contains("字符串b");
- Hello BIEE
这篇文章提供了一个Hello World式的例子,讲述如何创建一个最简单的BIEE资料库.本文使用的示例数据可以在从此链接下载:http://www.zw1840.com . 目录 创建资料库 创 ...
- 简单看看这两个类 String和StringBuilder
我记得以前在园子里面讨论这两个类的文章有很多很多,并且还拿出了很多的测试报告,在什么情况下,谁比谁快,在什么情况下,该用谁 不该用谁等等这些,我这里就不比较了,我就简单看看他们里面的内部实现,那就先看 ...
- 使用C/C++,赋值运算时发生的转换
使用C/C++,赋值运算时发生的转换主要有以下四种情况 一: 两边类型不同: 结果: 自动完成类型转换! 二: 长数赋给短数: 结果: 截取长数的低位送给短数! 三: 短数赋给长数: 结果: 原来是什 ...
- Qt5.5.0使用mysql编写小软件源码讲解---顾客信息登记表
Qt5.5.0使用mysql编写小软件源码讲解---顾客信息登记表 一个个人觉得比较简单小巧的软件. 下面就如何编写如何发布打包来介绍一下吧! 先下载mysql的库文件链接:http://files. ...
- 客户访问站点将bbs/链接 跳转至forum/链接下的两种方式
显性 302 暂时重定向跳转 server { listen 80 ; server_name localhost; index index.html index.htm index.php; roo ...
- php 连续留存与留存人数计算
for($i = 0;$i <= $interval;$i++) { $res = $model->turnround($today,$tomorrow,$flag); $temp = a ...
- 学习OpenStack之 (0):基础知识
vi 方向键出现字母问题解决方法 执行命令 sudo apt-get remove vim-common 执行命令 sudo apt-get install vim 鼠标被virtualbox捕获无法 ...