原文地址: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. chrome插件——Vimium 键盘手福利

    chrome插件——Vimium 键盘手福利 金刚 chrome chrome插件 Vimium 一直希望纯键盘操作,但是在浏览网页的时候,发现还是很难做到这点的.因为网页浏览的时候会有 各种各样的内 ...

  2. Token原理以及应用

    近期由于项目需要开发供第三方使用的api,在整个架构设计的一个环节中,对api访问需要进行认证,在这里我选择了token认证. 一:token的优势(此部分引自http://www.sumahe.cn ...

  3. Java基础知识学习(三)

    面向对象部分 首先要了解面向对象的思想,与C#一致,都是面向对象的语言 访问修饰符 public 共有的,对所有类可见. protected 受保护的,对同一包内的类和所有子类可见. private ...

  4. 你知道哪些linux命令,能把文件上传到远程linux服务器

    多数情况下 企业的服务基本都是部署在linux服务器 那对于测试同学,必须掌握基本的linux命令   至少要知道怎么部署整体环境   部署过程中,经常需要的操作,是向服务器上传部署包   你一般都是 ...

  5. .Net中使用aliases让相同命名空间的dll引用共存

    有些不得已的时候,我们需要同时在代码中使用某个dll的不同版本.比如用低版本的dll中的方法导出数据,然后使用高版本的方法导入数据来实现数据的升级. 又或者需要同时使用第三方的dll不同版本.如何使它 ...

  6. mysql数据校验之字符集问题

    场景:主库DB:utf8字符集备库DB:gbk字符集 需求:校验主备数据是否一致,并且修复 校验过程:设置主库连接为utf8,设置备库连接为gbk,分别进行查询,将返回的的结果集按记录逐字段比较. 显 ...

  7. nice

    我们在使用$top的时候有一列NI参数,这个参数就是进程的nice值,用来表示进程在系统调度中的优先级,Linux中的进程nice从-20到+19,越小表明调度的优先级越高,用户进程的最小nice值就 ...

  8. x01.os.8: 加载内核

    在 x01.os.7 中,借助 freedos,学习了保护模式.但操作系统必须完成引导:boot, 加载内核:loader,kernel,进而管理process,memory,file等. 引导比较简 ...

  9. php群发邮件,用数据库做邮件队列

    重思想,方法自己又写的,不能保证原文的都正确... Tutorial Tutorial – A tutorial for Mail_Queue Mail_Queue usage with a simp ...

  10. android setLayoutParams 问题,出错

    LinearLayout layt = (LinearLayout) rootView.findViewById(R.id.llt_2); FrameLayout.LayoutParams layou ...