Reputation: 7639
I have stripped my code down to the bare basics in so many ways trying to find out why the very first value in my array is blank and I am stumped. I have an array of directories and files. If it's a directory or a file whose names contains a certain string (like "conf"), I'm not interested. If it's anything else, I write it to the screen and push it to an array object.
Then, I loop through the array and write each entry to the screen. That's all I'm trying to do. When I view what is printed to the screen in the first part, the information is as I'd expect. When I print out the entries in the array, the output always has an empty string or nothing in the first index of the array.
Here's my code:
sub scrubFiles { # Parse through interesting directories for interestingly named files
my $wanted = sub {
if (-d $_) {
print "Directory and will not be inserted into the files array: $_\n"
return;
};
if ($_ =~ /\.(?:yaml|bak|conf|cfg)\z/i) {
print "Not desirable and will not be inserted into the files array: $_\n";
return;
};
print ("Adding $_ to \@filelist\n");
push @filelist, $File::Find::name;
};
find( {wanted => $wanted, no_chdir=>1}, @_ ); # WILL NOT work properly without no_chdir
return @filelist;
}
&scrubFiles("/tmp/mydirectory/");
for (@filelist) { print "File name: $_|END\n"; }
I get the following output when pushing to the array. The "<...>" is output I just removed because its irrelevant. The "Adding" section contains exactly what I'd expect. There is nothing before the first "Adding" printed to the screen. When it gets to the "File name" part, it's exactly as I'd expect except the first entry in the array printed out to the screen is blank, as you can see here:
Adding /tmp/mydirectory/ifconfig.txt to @filelist
Adding /tmp/mydirectory/history_comp.txt to @filelist
Adding /tmp/mydirectory/myctl.txt to @filelist
Adding /tmp/mydirectory/ls-l.txt to @filelist
<...>
Adding /tmp/mydirectory/opt/comp/VERSION to @filelist
File name: |END
File name: /tmp/mydirectory/ifconfig.txt|END
File name: /tmp/mydirectory/history_comp.txt|END
File name: /tmp/mydirectory/myctl.txt|END
File name: /tmp/mydirectory/ls-l.txt|END
<...>
File name: /tmp/mydirectory/opt/comp/VERSION|END
I've tried using "ref()" to figure out what's actually in position 0 but it returns nothing for each entry in the array.
Any ideas how I could be getting this blank entry?
Upvotes: 0
Views: 91
Reputation: 385789
The code you had previously had properly scoped variables. You broke that. By going back to using global variables, we have to see every line in your program to know what's going on. That would be daft.
Start by going back to the code you were given to undo the two bugs you introduced. Declare @filelist
in the sub, and actually use the list returned by the sub.
Upvotes: 1