Categories
Perl

Scanning directories with Perl

I often come across a task to do specific processing for each file at a subdirectory tree. Here is a skeleton code for what you need to get it started.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/perl
 
my $ROOTDIR = shift;
processDir($ROOTDIR);
 
exit 0;
 
# This is the main routine. Do not change it unless you know what you do!
sub processDir {
   my $dir = shift;
   my (@FILES, $entry, $path);
 
   if (opendir(DIRIN, $dir)) {
      @FILES = readdir(DIRIN);
      closedir(DIRIN);
 
      # iterate over dir entries
      foreach $entry (@FILES) {
         next if $entry eq '..';
         next if $entry eq '.';
         $path = "$dir/$entry";
 
         if (-f $path) {
            if (fileCheck($path)) {
               processFile($path);
            }
         } elsif (-d $path) {
            if (dirCheck($path)) {
               # recurse into subdir
               processDir($path);
            }
         }
      }
   }
}
 
# Do your file processing in this function only
# $file will have the complete path
sub processFile {
   my $file = shift;
}
 
# This function decides whether a file should be processed or not
# Return 1 when you want a file to be processed
# $file will have the complete path
sub fileCheck {
   my $file = shift;
   return 1;
}
 
# This function decides whether a directory should be searched recursively.
# Return 1 when you want the algorithm to steep into the directory.
# $dir will have the complete path
sub dirCheck {
   my $dir = shift;
   return 1;
}

You only will need to override lines 39-41. In case you don’t want to handle all files and directories, just make appropriate implementations in functions checkFile() and checkDir() respectively. This code works on all platforms.