I have the following question. Considder that in the directory /code the script remove.pl exists. What i want is to run this script and remove some files that exist in the directory /dir/tmp. I use the below code but it does not work.
Each system() call results in a call to a subshell. Once that subshell exits, it "forgets" which directory you told it to cd into, so the subsequent one knows nothing about it.
I'm sure there are built-in perl calls to do these file removals that don't require the invocation of a subshell which would be more efficient.
$command = /usr/bin/rm;
$dir = /path/to/something;
@files = ("filename1","filename2","filename3");
for $file(@files)
{
$args = "$command $dir/$file";
system $args;
}
Or as a subroutine
(this will allow you to send cp/rm/mv as well as changing the path)
sub doManageFiles($$@)
{
my $command = $_[0];
my $path = $_[1];
my $files = $_[2];
for (@{$files})
{
$args = "$command $path/$_";
system $args;
}
}
Of course, as perl is TIMTOWTDI, there are a few perl modules available via cpan that do file manipluation, such that you don't need to call an external "rm".
You don't need anything for simple deletes, just use unlink() for files and rmdir() for directories. Shelling out to delete files is a big waste. If you needed to zap an entire directory tree easily you could use File::Path.
Thanks for the tip, Kevin. I've used rmdir before, but I've not had a need for unlink...
The subroutine that I provided for my example was originally used for running some binaries against a handful of files - seemed easy enough to adapt for this.
I think that you've saved me a line or 5 going forward...