Put simply, I'm having problems modularizing some code into subroutines.
I'm creating a script to process directories and files on my website. I don't want all directories processed, just certain ones. To that end, I'm using an array to exclude certain directories, as shown below:
#!/usr/bin/perl use strict; use File::Find; # -| Configuration |------- my $basepath = '/sitedir/'; my @skipdirs = ( "private", "cgi-bin", "lib", "images", "files" ); # -| Main |---------------- find (\&findHandler, $basepath ); # -| Subs |---------------- sub findHandler { # -------------------------------------------------------- # Evaluates and processes found files; # init local vars my $filename = $File::Find::name; my $dircheck = ""; my $showfile = 1; # first, should we show this file? foreach $dircheck ( @skipdirs ) { $showfile = 1; if ( $filename =~ /$dircheck+/i ) { $showfile = 0; # skip this one; last; } } if ( $showfile ) # then do so { # first, strip leading path $filename =~ s/$basepath//i; # only after directory names. if ( -d ) # add dir to hash { print "$filename\n"; } } }
When run, the above behaves as I expect, printing a list of all directories that are not being excluded by the array. (Please note that the above has been stripped down for the sake of the question.)
However, when I try to break the directory validation bit into a separate subroutine, it no longer works. Instead, it prints all of the directories, including those that were excluded in the previous version. Here's what fails to work:
#!/usr/bin/perl use strict; use File::Find; # -| Configuration |------- my $basepath = '/sitedir/'; my @skipdirs = ( "private", "cgi-bin", "lib", "images", "files" ); # -| Main |---------------- find (\&findHandler, $basepath ); # -| Subs |---------------- sub findHandler { # -------------------------------------------------------- # Evaluates and processes found files; # init local vars my $filename = $File::Find::name; my $dircheck = ""; if ( goodDir( $filename ) ) # then do so { # first, strip leading path $filename =~ s/$basepath//i; # only after directory names. if ( -d ) # add dir to hash { print "$filename\n"; } } } sub goodDir { # -------------------------------------------------------- # Evaluates a file's dir to see if we want to print it. my $filename = $_; # file we're testing my $dircheck = ""; # loop counter my $showfile = 1; # assume success # first, should we show this file? foreach $dircheck ( @skipdirs ) { $showfile = 1; if ( $filename =~ /$dircheck+/i ) { $showfile = 0; # skip this one; last; # skip rest of loop; } } return $showfile; }
My question is: What am I doing wrong with my subdirectory definition? As afar as I can tell, the logic is precisely the same, though I strongly suspect I'm missing something extraordinarily simple, a Homerism.
Please note:
Thanks in advance for any suggestions...
--fIn reply to Problems creating sub's by footpad
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |