Monday, March 2, 2009

Perl Unlink Files on Windows

While working on a lab for one of my classes, I was writing a cgi script in Perl to manage log files for the web admin of a web site. I feel new to all things Perl and so debugging problems seems to take some time. TA's aren't much of a help and documentation online for my specific problem seemed scarce (it doesn't help when your not sure what the problem is).

The Problem:
The following script would not unlink files in the directory

#!"C:\xampp\perl\bin\perl.exe"

use strict;

my $url = "C:/xampp/htdocs/website/admin/logs";
my (@files);
opendir(DIR, $url);
@files = readdir(DIR);

print "Content-type: text/html\n\n";
my $file;
foreach $file (@files){
unlink $file;
}

close(DIR);

The Solution:
It seems that the $file variable doesn't actually point to the file but has a reference to the name of the file. For a while I kept thinking it had something to do with using unlink in Windows or file permissions. Through testing various things and getting some things to work, I found that by including the full path to the file when unlinking the files fixed my problem. My ending perl script looked like this:

#!"C:\xampp\perl\bin\perl.exe"

use strict;

my $url = "C:/xampp/htdocs/website/admin/logs";
my (@files);
opendir(DIR, $url);
@files = readdir(DIR);

print "Content-type: text/html\n\n";
my $file;
foreach $file (@files){
unlink $url . '/' . $file;
}

close(DIR);
Hopefully this post will save someone else time. Please let me know if this worked for you or the questions / comments you have. Thanks.

References:
This site gave me some good ideas that helped me figure out the solution.
www.issociate.de