Remove files from a directory using perl

Hi all,

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.

system("cd /dir/code");
system("rm FileName");

Best Regards,
Christos

Try:

system("cd /dir/code; rm FileName");

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.

unlink "/dir/code/FileName";

The cd is Useless in the system() invocation too, you can obviously use a path name with rm as well.

He wants to unlink from the temp directory, so:

unlink "/dir/temp/filename"

Here's another way

$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... :slight_smile:

Cheers,

  • Avron