http://www.perlmonks.org?node_id=1066933


in reply to Trouble with File::Find::Rule

I definitely agree with 2teez that you should probably not hard code the directories and the number of such directories. Or, if you do nonetheless, do it in a way that is easy to change. For example, this loop:
while($count < 2) { print $count; $directory = 'C:\Test\Calls\Archive' if $count eq 0; $directory = 'C:\Test\Calls\History' if $count eq 1; @files = File::Find::Rule->file() ->name( "*.wma", "*.wmv" ) + ->in( $directory ); $count++; }
could possibly be rewritten as follows:
my $base_dir = 'C:\Test\Calls\'; my @directories = $base_dir . $_ . '\' for qw /History Archive/; my @files; for my $dir (@directories) { push @files, $_ for glob ($curr_dir . "*.wma"), glob ($curr_dir . + "*.wmv"); }
This might still not be not the best way to do it, but the advantage, at least, is that if you need to add another subdirectory, you only need to add it to the @directories array and don't need to change anything else. The last line in the code above is not very satisfactory, because the extensions are hard coded. So you could change it to nested loops:
my $base_dir = 'C:\Test\Calls\'; my @directories = $base_dir . $_ . '\' for qw /History Archive/; my @extensions = qw /wma wmv/; my @files; for my $dir (@directories) { for my $ext (@extensions) { push @files, $_ for glob ($curr_dir . $ext); } }
Now, if you need an additional extension, there is only one place where it needs to be modified. This is untested, as I do not have Perl under Windows available right now.

Replies are listed 'Best First'.
Re^2: Trouble with File::Find::Rule
by tbone654 (Beadle) on Dec 13, 2013 at 02:15 UTC

    I use this code chunk quite a bit to get directory contents without extra modules, and the nice thing is you only change one line to re-direct to another location, or you use a variable that you pass to it...


    This particular version sorts the list and reads the contents of the files into an array, if that is of any value. The array dots is a list of all the files in the directory that you can grep for a pattern and work with.

    $sd = "../data"; opendir( DIR, $sd) || die; while( ($filename = readdir(DIR))){ next if "$sd\/$filename" =~ /\/\./; push @dots, "$sd\/$filename"; } ## end of while @dots = sort @dots; closedir(DIR); for($a=0;$a<@dots;$a++){ open (FILE, $dots[$a]); push @foo, <FILE>; close FILE; } ## end of for
      tbone654, thanks for the code! I have used something similar in the past as well but in this case I need to go into all the subfolders of the root folder, thats why I was using File::Find::Rule.