Search code examples
regexperlrecursionfinddirectory-traversal

Premature exit from Perl File::Find


In Perl we usually do a recursive directory traversal using File::Find and we often use code similar to below to find certain files based on a pattern.

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

This is generally quite flexible, but there are certain times when we want to prematurely exit the find. Is there a defined way in Perl to do this?


Solution

  • Try if this possibility could work for you:

    die inside find function and surround the call in an eval function to trap the exception and continue execution your program.

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

    And inside filter function:

    sub filter {
        my $srcfile = $_;
        if -f $srcfile && $srcfile =~ /<CERTAIN PATTERN>/ {
            die "Premature exit";
        }
    }