原文地址: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?的更多相关文章

  1. 网站访问出现 ------ Can not write to cache files, please check directory ./cache/ .

    最近在搞微商城时,突然出现了Can not write to cache files, please check directory ./cache/ .这样一个提示, 但最近好像没搞什么大动作,怎么 ...

  2. [Windows API] Listing the Files in a Directory,可用来数文件夹下有多少个子文件(夹)

    转载 #include <windows.h> #include <tchar.h> #include <stdio.h> #include <strsafe ...

  3. Batch the files in the directory

    #!/bin/bash #sourceFolder = /home/bigdatagfts/pl62716/refdata #targetFolder = /home/bigdatagfts/pl62 ...

  4. 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 ...

  5. 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 ...

  6. Files and Directories

    Files and Directories Introduction     In the previous chapter we coveredthe basic functions that pe ...

  7. 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 ...

  8. 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 ...

  9. 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 ...

随机推荐

  1. raw_input() 与 input() __ Python

    这两个均是 python 的内建函数,通过读取控制台的输入与用户实现交互.但他们的功能不尽相同.举两个小例子. 1 >>> raw_input_A = raw_input(" ...

  2. 对js中Function的浅见

    它到底是什么 String Array 都是系统内置对象(已经定义好,可以直接使用)当然,这货也是一样,我们之前定义的函数,其实就是一个这货的实例. 在JS中,所有的对象都是由函数实现的,函数的数据类 ...

  3. nutz如何体现mvc思想的

    如何理解web mvc框架?? 一.没有使用mvc框架之前我们都是自己根据mvc分层思想的理解去把它物理化,比如:根据包的命名,根据类的后缀名,根据文件夹的命名去定义分层. 因为每个人对mvc的理解不 ...

  4. [PL/SQL]oracle数据库的导出导入

    一.PL/SQL Developer工具一般对oracle的导入导出有以下4中方式: 1.Oracle导出导入方式 这种方式导出导入为.dmp的文件格式,.dmp文件是二进制的,可以跨平台,还能包含权 ...

  5. 小议如何使用APPLY

    简介 如果你打算为在结果集中的每条记录写一个调用表值函数或者表值表达式的select语句,那么你就能用到APPLY 操作符来实现.一般又两种形式写法: 第一种格式就是CROSS APPLY.这种格式可 ...

  6. hadoop2.4.1集群搭建

    准备Linux环境 修改主机名: $ vim /etc/sysconfig/network NETWORKING=yes HOSTNAME=hadoop001 修改IP: # vim /etc/sys ...

  7. 使用dwr时动态生成table的一个小技巧

    这篇随笔是我在07年写的,因为当时用了自己建设的blog,后来停止使用了,今天看到备份数据库还在,恢复出来放到这里.留着记录用. 我在使用DWR时,试了很多次都无法在动态生成的table中的一个或多个 ...

  8. YUV420查表法高效、无失真的转换为RGB32格式

    YUV格式有两大类:planar和packed.planar的YUV格式,先连续存储所有像素点的Y,紧接着存储所有像素点的U,随后是所有像素点的V,这里所讲述的就是这中存储格式的:packed的YUV ...

  9. iNeedle系统之国舜项目

    一.简介 本周公司接了一个小项目,是给北京国舜科技股份有限公司做一个HTTP相关的小功能产品.大概实现功能是将交换机的源数据通过解析,分析出HTTP包配对的request和response头,并把每对 ...

  10. 《C陷阱与缺陷》之1词法"陷阱"

    编译器中负责将程序分解为一个一个符号的部分,一般称为"词法分析器".在C语言中,符号之间的空白(包括空格符.制表符或换行符)将被忽略. 1.=不同于== C语言使用符号" ...