Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I break out of recursive find function once a specific file is found?

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?
      }
   }
like image 582
MCS Avatar asked Dec 19 '08 16:12

MCS


People also ask

How do you escape a recursive function?

A first way to escape recursion is to evaluate everything then return 0 when the input list is empty. A second way to escape recursion is to evaluate everything but the last element, then either return the last thing or do something to the last thing and then return the result of that last function.

How do you stop a recursive function in python?

Also, a recursive function needs to have a condition to stop calling itself. So you need to add an if statement like this: def fn(): # ... if condition: # stop calling itself else: fn() # ...


2 Answers

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';
   }
}
like image 169
innaM Avatar answered Oct 18 '22 21:10

innaM


In addition to what everyone else said, you may wish to take a look at File-Find-Object, which is both iterative (and as such capable of being interrupted in the middle) and capable of instantiation (so you can initiate and use several at once, or instantiate an F-F-O object based while performing another scan, etc.)

The downside for it is that it isn't core, but it only has Class::Accessor as a dependency, and is pure-Perl so it shouldn't be hard to install.

I should warn you that I am its maintainer, so I may be a bit biased.

like image 39
Shlomi Fish Avatar answered Oct 18 '22 23:10

Shlomi Fish