2

在 Perl 中,我们通常使用递归目录遍历,File::Find并且我们经常使用类似于下面的代码来根据模式查找某些文件。

find(\&filter, $somepath);
sub filter {
    my $srcfile = $_;
    if -f $srcfile && $srcfile =~ /<CERTAIN PATTERN>/ {
        <Some processing which requires a premature exit>
    }
}

这通常非常灵活,但有时我们想提前退出查找。Perl 中是否有明确的方法来执行此操作?

4

2 回答 2

3

试试这种可能性是否对您有用:

die内部find函数并将调用包围在eval函数中以捕获异常并继续执行您的程序。

eval { find(\&filter, $somepath) };
print "After premature exit of find...\n";

和内部filter功能:

sub filter {
    my $srcfile = $_;
    if -f $srcfile && $srcfile =~ /<CERTAIN PATTERN>/ {
        die "Premature exit";
    }
}
于 2011-12-31T17:44:21.363 回答
2

你可以这样做:

#!/usr/bin/env perl
use strict;
use warnings;
use File::Find;
my $somepath = q(.);
my $earlyexit;

find(\&filter, $somepath);
sub filter {
    my $srcfile = $_;

    $File::Find::prune = 1 if $earlyexit; #...skip descending directories

    return if $earlyexit;                 #...we have what we wanted

    if (  -f $srcfile && $srcfile =~ /<CERTAIN PATTERN>/ ) {
    #...<Some Processing which requires premature exit>
    #   ...
        $earlyexit = 1;
    }
}
于 2011-12-31T17:47:27.513 回答