原文地址: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. windows 常用命令

    1 Services.msc  在运行输入 启动所有安装程序配置

  2. nginx 配置优化的几个参数(转)

    nginx配置文件里面需要注意的一些参数 worker_processes 8  nginx要开启的进程数 一般等于cpu的总核数 其实一般情况下开4个或8个就可 我开2个 以了 多了没有太多用每个n ...

  3. MySql技巧个人笔记

    1.数据null时sum的用法 mysql数据库SUM(A+B)不一定等于SUM(A)+SUM(B),当A或B为NULL时,SUM(A+B)=NULL. 2.or改为in 同一字段,将or改写为in( ...

  4. Sql Server之旅——第六站 使用winHex利器加深理解数据页

    这篇我来介绍一个winhex利器,这个工具网上有介绍,用途大着呢,可以用来玩数据修复,恢复删除文件等等....它能够将一个file解析成 hex形式,这样你就可以对hex进行修改,然后你就可以看到修复 ...

  5. WEB压力测试

    原文地址:WEB压力测试 作者:鸟哥のlinux webbench最多可以模拟3万个并发连接去测试网站的负载能力,个人感觉要比Apache自带的ab压力测试工具好,安装使用也特别方便. 1.适用系统: ...

  6. Python基本语法,python入门到精通[二]

    在上一篇博客Windows搭建python开发环境,python入门到精通[一]我们已经在自己的windows电脑上搭建好了python的开发环境,这篇博客呢我就开始学习一下Python的基本语法.现 ...

  7. javascript 基础教程[温故而知新一]

    子曰:“温故而知新,可以为师矣.”孔子说:“温习旧知识从而得知新的理解与体会,凭借这一点就可以成为老师了.“ 尤其是咱们搞程序的人,不管是不是全栈工程师,都是集十八般武艺于一身.不过有时候有些知识如果 ...

  8. 工作中常用的Linux命令:ipcs/ipcrm命令

    本文链接:http://www.cnblogs.com/MartinChentf/p/6057100.html (转载请注明出处) ipcs 1. 命令格式 ipcs [resource-option ...

  9. java报表工具FineReport的公式编辑框的语法简介

    FINEREPORT用到公式的地方非常多,单元格(以=开头的便被解析为公式),条件显示,数据字典,报表填报属性值定义,图表标题,轴定义,页眉页脚,甚至单元格的其他属性中的鼠标悬浮提示内容都可以写公式, ...

  10. 广州APP开发外包公司哪家比较好?广州达到信息技术有限公司技术到底怎么样?

        广州APP开发公司哪家比较好,广州手机APP软件开发公司广州达到信息表示:用户的刚性需求是公司使用手机APP软件盈利的根本前提和基础,所以开发一款手机APP应用时必须从客户的角度来思考.因此公 ...