Gossamer Forum
Home : General : Perl Programming :

Perl unlink

Quote Reply
Perl unlink
The question is how to use the unlink command to delete all the files in a given directory? For example, /usr/myhome/fun/. How would I use wildcard characters with unlink?

Thanks in advance... Dan Smile
Quote Reply
Re: Perl unlink In reply to
Short answer, you can't. unlink() is safe that way in that it doesn't interpret shell characters so if you try to:

unlink ('a*.*')

it will only erase one file named a*.*.

What you can do is (probably an easier way using globs, but I'm not that familiar with them):

opendir (DIR, '/dir/to/delete') or die $!;
@files = grep /\.bat$/, readdir(DIR);
closedir DIR;

foreach $file (@files) {
unlink ("/dir/to/delete/$file") or die $!;
}

Modify the /\.bat/ to mask the files you want to remove.

Or if you don't care about being cross platform, and are on unix, just do:

system ('rm /dir/to/delete/*.bat') or die $!;

Cheers,

Alex
Quote Reply
Re: Perl unlink In reply to
Thanks Alex for the prompt answer to my question! As it is for personal purposes and I stick with UNIX, the system ('rm /dir/to/delete/*.bat') or die $!; suggestion works perfect.

I'm modifying the nph-build.cgi script to run as a cron job daily and I wanted to delete the backup and New files before building:

system ('rm /home/serve/bluewavelinks/scripts/admin/backup/*');
system ('rm /home/serve/bluewavelinks/New/*');

I knew the rm line to use but how to implement it in a script until you put forth the system command.

BTW, when you use a script for cron, does it matter if it produces HTML output? I've created a new file (cron.cgi) from nph-build.cgi and added the lines above and deleted the output lines.

Thanks again... Dan Smile
Quote Reply
Re: [dan] Perl unlink In reply to
Hi,

I believe regular expressions work when enclosed within pair of <> when used with unlink.
unlink (<a*.*>); #this will work and remove files matching a*.*

Regards,
Vinayak Bhat