Sadmachine has asked for the wisdom of the Perl Monks concerning the following question:

I'm a bit of a Perl newbie (7 days and counting) and I need help! I'm trying to write some code that will delete all files in a specified directory on an NT4 server.
opendir(DIR, "$basedir/$mesgdir"); @allfiles = readdir(DIR); @onlyfiles = grep {!/^\./} @allfiles; foreach $file (@onlyfiles) { unlink ($file); } closedir(DIR);
As far as I can tell the above code should work. I know that opendir uses the correct directory, I know that a list of files is created (@allfiles) and that @onlyfile is a list of files minus the dot files. The only bit that doesn't work is the unlink part. Can anyone tell me why? Thanks

Replies are listed 'Best First'.
Re: Deleting specified files and directories
by MeowChow (Vicar) on May 14, 2001 at 12:09 UTC
    unlink will operate on files in the current directory, if you haven't provided a fully-specified path when calling it. Try:
    foreach my $file (@onlyfiles) { unlink "$basedir/$mesgdir/$file"; }
    Also, you will be virtually tarred and feathered unless you use strict, turn on warnings (#!/usr/bin/perl -w), and check for errors after system calls (such as opendir).
       MeowChow                                   
                   s aamecha.s a..a\u$&owag.print
Re: Deleting specified files and directories
by Corion (Patriarch) on May 14, 2001 at 12:03 UTC

    The only small part you're missing is, that your files are not in the current directory but in $basedir/$mesgdir. Otherwise, your code seems fine, but using unlink $file or die "Couldn't delete $file : $!\n" is a method to catch your errors earlier :)

    Another thing is, you seem not to be using strict;. This would not have helped in this case, but use strict; is a good habit to start with early.

Re: Deleting specified files and directories
by Eureka_sg (Monk) on May 14, 2001 at 12:11 UTC

    Hi , when you use unlink you need to specify the full pathname of the file, such as

     unlink "$basedir/$mesgdir/$file"

    Check out this node Re: File Attributes in Win32 for my reply to a similiar problem : )

    UPDATE: Put the pathname in double quotes. Thanks to MeowChow's reminder

      Thanks to everyone for the help. I'll add in all those things suggested. I don't want to be virtually tarred and feathered ;-) Thanks