Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use File::Find in Perl?

Tags:

I'm a bit confused from File::Find documentation... What is the equivalent to $ find my_dir -maxdepth 2 -name "*.txt"?

like image 646
David B Avatar asked Sep 25 '10 20:09

David B


People also ask

How do I search for a file in Perl?

Find modules in Perl has all the functions similar to the Unix Find command. Find function takes two arguments: 1st argument is a subroutine called for each file which we found through find function. 2nd argument is the list of the directories where find function is going to search the files.

How do I check if a file exists in Perl?

Perl has a set of useful file test operators that can be used to see whether a file exists or not. Among them is -e, which checks to see if a file exists.

How do I search for a string in a text file in Perl?

Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text.


1 Answers

Personally, I prefer File::Find::Rule as this doesn't need you to create callback routines.

use strict; use Data::Dumper; use File::Find::Rule;  my $dir = shift; my $level = shift // 2;  my @files = File::Find::Rule->file()                             ->name("*.txt")                             ->maxdepth($level)                             ->in($dir);  print Dumper(\@files); 

Or alternatively create an iterator:

my $ffr_obj = File::Find::Rule->file()                               ->name("*.txt")                               ->maxdepth($level)                               ->start($dir);  while (my $file = $ffr_obj->match()) {     print "$file\n" } 
like image 64
justintime Avatar answered Sep 22 '22 05:09

justintime