Perl:如何停止 File::Find 递归进入目录? [英] Perl: How to stop File::Find entering directory recursively?

查看:52
本文介绍了Perl:如何停止 File::Find 递归进入目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看 Perl 的 File::Find 模块并按以下方式尝试:

I was looking at Perl's File::Find module and tried it in the following way:

#!/usr/bin/perl

use warnings;
use strict;

use File::Find;

find({wanted => \&listfiles,
        no_chdir => 1}, ".");


sub listfiles{
    print $File::Find::name,"\n";
}

现在当我运行它时,我得到以下输出:

Now When I run it I get the below output:

Noob@Noob:~/tmp$ perl test.pl 
.
./test.txt
./test.pl
./test1.txt
./hello
./hello/temp.txt

现在,我想通过设置 no_chdir=>1 我会让我的代码在遇到任何目录时不进入任何目录.但是输出清楚地表明我的代码正在进入 hello 目录并列出其文件.

Now, I was thinking that by setting no_chdir=>1 I will make my code to not enter any directory if it came across one. But the output clearly shows that my code is entering hello directory and listing its files.

那么,如何更改我的代码以使其行为类似于 ls 并且不进入任何目录.另外我在我的文件/目录名称前面得到 ./ 可以删除吗?

So, how do I change my code to behave like ls and not enter any directory. Also I am getting ./ in front of my file/directory names can that be removed?

我使用的是 Perl 5.14.

I am using Perl 5.14.

推荐答案

$File::Find::prune 可用于避免递归到目录中.

$File::Find::prune can be used to avoid recursing into a directory.

use File::Find qw( find );

my $root = '.';
find({
   wanted   => sub { listfiles($root); },
   no_chdir => 1,
}, $root);

sub listfiles {
   my ($root) = @_;
   print "$File::Find::name\n";
   $File::Find::prune = 1  # Don't recurse.
      if $File::Find::name ne $root;
}

如果您愿意,您可以有条件地设置 prune.

You can set prune conditionally if you so desire.

use File::Basename qw( basename );
use File::Find     qw( find );

my %skip = map { $_ => 1 } qw( .git .svn ... );

find({
   wanted   => \&listfiles,
   no_chdir => 1,
}, '.');

sub listfiles {
   if ($skip{basename($File::Find::name)}) {
      $File::Find::prune = 1;
      return;
   }

   print "$File::Find::name\n";
}

no_chdir 不是必需的 —它与您尝试做的事情无关—但我喜欢它的作用(防止改变 cwd),所以我把它留在了.

no_chdir is not necessary — it has nothing to do with what you are trying to do — but I like what it does (prevents changes to the cwd), so I left it in.

这篇关于Perl:如何停止 File::Find 递归进入目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆