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

Hi. I am having a problem with my script checking to see if a file exists, and if so, deleteing it.

The script is run from the D: drive of the computername John. It is checking in the c:\daily directory for a file name daily_count_by_userid_and_domain.xls. This is just part of my existing script, since the rest of it works. Below is my code.

What I am doing wrong? How can I ensure that this file exists at the start of the script and that it will be deleted? I'm very sorry to have to ask what should be such an easy question.

#!d:\perl\bin use File::Copy; my $filename ='daily_count_by_userid_and_domain.xls'; my $path = '\\\\John\\c$\\daily\\'; my $nfile = '_daily_count_by_userid_and_domain.xls'; my $test = 'outputfile.txt'; ($Second, $Minute, $Hour, $DayOfMonth, $Month, $Year, $WeekDay, $DayOfYear, $IsDST) = localtime(time); my $real = $Year + 1900; my ($d,$m) = (localtime)[3,4]; my $date = sprintf("%02d%02d",++$m,$d,); my $npath = '\\\\Bob\\scripts\\security\\public\\'; my $complete = '$path$filename'; opendir (HOLDING, 'C:\daily'); chdir 'C:\daily'; @asci = glob ('*.xls'); foreach $asci (@asci) { if ($asci =~ /$asci/) system ("del $asci"); } system("\"C:\\Program Files\\Microsoft Office\\Office\\MSACCESS.EXE\" d:\\imas_security\\imas_security.mdb /x auto_update"); open(OUT, ">>$test"); copy ("$path$filename", "$npath$real$date$nfile"); closedir(HOLDING); close (OUT);

MHTIA.

Replies are listed 'Best First'.
Re: Searching for a file, confirming that it exists, then deleting it
by chromatic (Archbishop) on Apr 11, 2002 at 19:39 UTC
    You might have better luck with -e $filename and unlink.
Re: Searching for a file, confirming that it exists, then deleting it
by tadman (Prior) on Apr 11, 2002 at 19:59 UTC
    A couple of tricks might be helpful with your application.
    • Instead of using a system call, use unlink
    • $filename and $nfile: $nfile = "_$filename" perhaps?
    • Don't permanently mangle your variables for a temporary use, like you did when processing your date: my $date = sprintf ("%04d%02d%02d", $year+1900, $m+1, $d)
    • Strip out any variables that are no longer used, such as the apparently orphaned $complete.
    • if($asci =~ /$asci/) translates to "If this matches itself", which is an unreliable way to say "if (1)". Remember that '.' and '*', among other things, are different in regular expressions.
    • As chromatic pointed out, you can test for a file using the '-e' function instead of reading the directory table. Used something like: if (-e $file)
    • Rember that if statements must have braces, unless the if comes after the statement (i.e. $x = 1 if ($foo);). You are using a C-style if here and it will not work as you expect, if at all.
    As a general note, your code is highly cluttered and confusing, which is going to make it hard to maintain. Some effort spent organizing and reducing it would probably help appreciably.