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?
}
}
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.
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() # ...
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';
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With