I need to write a function in Perl that removes all files with the .rc
suffix under a certain location and its subdirectories (lets call it targetroot).
I am working in NT env, so I can't use system commands like find
, or rm
.
I have tired to do it with unlink and find options but didn't manage.
What I have tried is:
print "\n<<< Removing .rc files from $targetRoot\\20140929_231622 >>>\n";
my $dir = "$targetRoot\\20140929_231622";
find(\&wanted, $dir);
sub wanted
{
unlink glob "*.rc";
}
Can someone show me how to do it?
You're pretty close. File::Find
is the tool for the job here. Try putting your wanted()
as:
sub wanted {
# $_ set to filename; $File::Find::name set to full path.
if ( -f and m/\.rc\z/i ) {
print "Removing $File::Find::name\n";
unlink ( $File::Find::name );
}
}
Try it first without the unlink of course, to verify you get the right targets. Bear in mind File::Find
will recurse down the directory structure by default.
You need to modify the wanted
subroutine:
sub wanted { /\.rc$/ && ( unlink $File::Find::name or die "Unable to delete $_: $!" ) }
From the File::Find
documentation
The
wanted
functionThe
wanted()
function does whatever verifications you want on each file and directory. Note that despite its name, thewanted()
function is a generic callback function, and does not tellFile::Find
if a file is "wanted" or not. In fact, its return value is ignored.The wanted function takes no arguments but rather does its work through a collection of variables.
`$File::Find::dir` is the current directory name, `$_` is the current filename within that directory `$File::Find::name` is the complete pathname to the file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With