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

2 comments:

Wolf said...

Perl is the best scripting language for Text processing and handle regex. I have posted few articles related to those at my blog

http://icfun.blogspot.com/search/label/perl

Also Perl's Cpan has lots of support that I don't even need to think extra while developing project. I didn't find such help on other programming language except Java and .NET

Deborah said...

Any idea how to use unlink on a file with the hidden attribute set?