I am newbie at Perl. I am trying to write a Perl script that prints the content of all the files in a directory and recursively do it till all the files in the directories/sub-directories are printed. I am doing it with the following subroutine.
sub print_files_in_dir {
my $file = shift;
if(-d $file){
my @files=glob "$file/*";
foreach my $file (@files){
if(-d $file){
print_files_in_dir $file;
}
else {
print_file $file;
}
}
else {
print_file $file;
}
}
where print_file is sub which prints the content of a single file. I get this error with I try to execute this code with a directory say dir1 which contains another directory named dir2.
Can’t locate object method “print_files_in_dir” via package “dir1/dir2” (perhaps you forgot to load “dir1/dir2”?)
Cant figure out why is it throwing this error ?
As you learned, omitting parens around argument lists can give you really weird errors. Some are even silent. For example,
print (4+6)*2prints10! (ok, it’ll warn if you have warnings on as you should, so it’s not really silent, but it’s not fatal either.) One must be careful if one is omits those parens.I’m writing this because I noticed a problem with your
glob; it won’t work if the path has certain characters in them, such as spaces.should be
And since I’m here, there’s a bit of redundancy that can be eliminated. Your sub collapses to:
Actually, you could use File::Find::Rule to collapse it further.