如何获取目录及其子目录中的文件句柄?

Eli*_*Eli 3 perl

因此,我最近注意到在脚本中使用了opendir,并希望稍微更改它,以便它返回目录的子文件夹中的文件以及目录本身中的文件.在调查之后,我无法为opendir找到任何类型的递归选项,并且在使用glob返回标量时遇到了麻烦.因此,我认为只要问一下:在dir及其子目录中处理所有文件的标准方法是什么,而不是用另外一个进行捏造.

FMc*_*FMc 7

经典的方法是使用File :: Find,它具有成为核心模块的优势,但它可能有点痛苦.如果您能够使用第三方模块,File :: Util非常方便:

use File::Util;
my $fu = File::Util->new;

my $root = 'foo/bar';

my @dirs_and_files = $fu->list_dir($root, '--recurse');
my @files_only     = $fu->list_dir($root, '--recurse', '--files-only');
Run Code Online (Sandbox Code Playgroud)


Set*_*son 5

find2perl为目录树中的所有文件生成递归调用的示例代码.

> find2perl . -type f -print
#! /usr/bin/perl -w
    eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
        if 0; #$running_under_some_shell

use strict;
use File::Find ();

# Set the variable $File::Find::dont_use_nlink if you're using AFS,
# since AFS cheats.

# for the convenience of &wanted calls, including -eval statements:
use vars qw/*name *dir *prune/;
*name   = *File::Find::name;
*dir    = *File::Find::dir;
*prune  = *File::Find::prune;

sub wanted;



# Traverse desired filesystems
File::Find::find({wanted => \&wanted}, '.');
exit;


sub wanted {
    my ($dev,$ino,$mode,$nlink,$uid,$gid);

    (($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_)) &&
    -f _ &&
    print("$name\n");
}
Run Code Online (Sandbox Code Playgroud)

根据需要将其用作模板.