原文地址: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. 【开源项目SugarSite】ASP.NET MVC+ Layui+ SqlSugar+RestSharp项目讲解

    SugarSite一个前端支持移动端的企业网站,目前只支持了简单功能,后续还会加上论坛等. 源码GIT地址: https://github.com/sunkaixuan/SugarSite 技术介绍 ...

  2. juqery 实现 防止当前页面重复点击,以减轻服务器压力

    <script> //防止当前页面重复点击,以减轻服务器压力 $(document).ready(function () { var current_url = location.path ...

  3. 导入导出oracle数据库表的dmp文件

    1.先进入命令行,点击开始,输入cmd 2.导入的命令是:imp 用户名/密码@网络服务名 file=xxx.dmp full=y; 3.导出的命令是:exp 用户名/密码@网络服务名 file=xx ...

  4. ListView的监听器中OnItemClick各个参数的作用

    方法的原型如下 public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){ } 后面有4个参 ...

  5. ksvcreate: Process(m000) creation failed

    一测试服务器数据库(Oracle Database 10g Release 10.2.0.5.0 - 64bit Production)突然访问不了,检查发现数据库处于挂起模式(hang mode), ...

  6. jq+css+html简单实现导航下拉菜单

    相信导航栏下拉菜单是web开发最常见的一个item了.这里就不做介绍了,直接上code. Html部分 <div class="_nav"> <ul id=&qu ...

  7. 走进云背后:微软Azure web 项目通过web service部署web site

    探索云那不为人知的故事(一):Web Services部署web site 前奏:Windows Azure是微软基于云计算的操作系统,现在更名为“Microsoft Azure”,和Azure Se ...

  8. Centos和Redhat的区别和联系

    网上看到的,转载给大家 CentOS与RedHat的关系: RedHat在发行的时候,有两种方式:二进制的发行方式以及源代码的发行方式.无论是哪一种发行方式,你都可以免费获得(例如从网上下载),并再次 ...

  9. C#基础---事件的使用

    一:什么是事件     事件是可以被控件识别的操作,如按下确定按钮,选择某个单选按钮或者复选框.每一种控件有自己可以识别的事件,如窗体的加载.单击.双击等事件,编辑框(文本框)的文本改变事件,等等.事 ...

  10. POJ 1696 Space Ant 【极角排序】

    题意:平面上有n个点,一只蚂蚁从最左下角的点出发,只能往逆时针方向走,走过的路线不能交叉,问最多能经过多少个点. 思路:每次都尽量往最外边走,每选取一个点后对剩余的点进行极角排序.(n个点必定能走完, ...