R – How to break out of recursive find function once a specific file is found

file-findperlrecursion

I'm using the File::Find module to traverse a directory tree. Once I find a specific file, I want to stop searching. How can I do that?

   find (\$processFile, $mydir);

   sub processFile() {
      if ($_ =~ /target/) {
         # How can I return from find here?
      }
   }

Best Answer

Seems like you will have to die:

eval {
    find (\$processFile, $mydir);
};

if ( $@ ) {
   if ( $@ =~ m/^found it/ ) {
        # be happy
    }
    else ( $@ ) {
        die $@;
    }
}
else {
   # be sad
}


sub processFile() {
   if ($_ =~ /target/) {
      die 'found it';
   }
}