Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi,
I am using File::Find to recursively search the directories for a file. I want to return TRUE as soon as there is a match. I am using the following code snippet.
($languagefile) = find(\&search_localdir, $local_inst_dir);
sub search_localdir { chomp($FILE_TO_FIND); if ($FILE_TO_FIND eq $_){ print "SRC:$FILE_TO_FIND\nDES:$_\n"; return $File::Find::name; } return 0; }
Problem here is it is not returning when there is a match. It continues to check the remaining files also. What I want is, it should return the filename and transfer the control to main program without further find. Please help me to achieve that.
Thanks,

Replies are listed 'Best First'.
Re: Problem - Recursive file find using File::Find
by CountZero (Bishop) on May 14, 2009 at 09:17 UTC
    What you need is an iterator. Higher Order Perl - Iterators says some very interesting things in that respect.

    For the time being however, you can perhaps use File::Find::Rule (rather than File::Find), which has a method match which returns after each file found.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: Problem - Recursive file find using File::Find
by moritz (Cardinal) on May 14, 2009 at 09:04 UTC
    Look at the docs, there's a $File::Find::prune variable that you can set if you want to skip subdirectories.

    If you want to terminate processing altogether, throw an exception with die, and catch it on the outside with eval.

Re: Problem - Recursive file find using File::Find
by duff (Parson) on May 15, 2009 at 00:20 UTC

    What CountZero said. Luckily, there's a module on CPAN that gives you a file finding iterator: File::Next