Perl子例程以递归方式返回目录中的所有文件

时间:2016-02-17 08:23:41

标签: perl

我是perl的新手,虽然我可以编写代码来打印perl目录中的所有文件名,但我不知道如何编写一个子程序,它会将相同的函数返回给它的调用函数

3 个答案:

答案 0 :(得分:3)

使用File::Find模块:

#! /usr/bin/perl
use warnings;
use strict;

use File::Find;

sub get_all_files {
    my ($dir) = @_;
    my @files;
    # Use $File::Find::name instead of $_ to get the paths.
    find(sub { push @files, $_ }, $dir);
    return @files
}

my $dir = shift;
my @files = get_all_files($dir);
print "$_\n" for @files;

答案 1 :(得分:1)

试试这个 您只想使用print str(cuteCatNum)模块将文件搜索到目录中。否则你应该创建递归子程序来做到这一点。

File::Find

此处my $path = "/home"; find($path); sub find{ my ($s) = @_; foreach my $files (glob "$s/*") { if(-f $files) { print "$files \n"; } elsif(-d $files) { find("$files") } } } 表示内容为目录。 -d表示内容为文件。

首先将目录名称传递给find子例程。然后使用$ s变量获取值,glob/*列出路径中的所有文件。然后迭代特定目录文件的循环。如果文件存在,则它会出现在-f块中,如果存在文件夹,则它会进入if。然后文件夹名称再次转到子程序,依此类推。

答案 2 :(得分:0)

学习在文档中查找内容。

以" perldoc perlfaq"开始你会发现:

   perlfaq5 - Files and Formats

然后看看" perldoc perlfaq5"并搜索"目录"。你会发现:

如何遍历目录树?        (由brian d foy提供)

   The File::Find module, which comes with Perl, does all of the hard work to traverse a
   directory structure. It comes with Perl. You simply call the "find" subroutine with a
   callback subroutine and the directories you want to traverse:

       use File::Find;

       find( \&wanted, @directories );

       sub wanted {
           # full path in $File::Find::name
           # just filename in $_
           ... do whatever you want to do ...
       }

   The File::Find::Closures, which you can download from CPAN, provides many ready-to-use
   subroutines that you can use with File::Find.

   The File::Finder, which you can download from CPAN, can help you create the callback
   subroutine using something closer to the syntax of the "find" command-line utility:

       use File::Find;
       use File::Finder;

       my $deep_dirs = File::Finder->depth->type('d')->ls->exec('rmdir','{}');

       find( $deep_dirs->as_options, @places );

   The File::Find::Rule module, which you can download from CPAN, has a similar interface,
   but does the traversal for you too:

       use File::Find::Rule;

       my @files = File::Find::Rule->file()
                                ->name( '*.pm' )
                                ->in( @INC );