in reply to -z file test operator

It looks like you apply the test to an open filehandle and then try unlinking with the same handle. Unlinking should be done on the filename. The -z test should be done after the filehandle is closed to ensure all data is written. Unlinking an open file is Not Good. This is better:

# assumes the file is named in a variable $badsyms. # $badsyms would best be an absolute path. # # close(BADSYMS); before this, otherwise writes may not be # flushed before the test. # That would give a false positive if ( -z $badsyms ) { unlink $badsyms or die "Cannot unlink $badsyms: $!"; } else { print "Bad symbols contained in $badsyms\n"; }
It would be helpful to see what kind of loop this is in and how the filenames are obtained. I may have misunderstood what you are doing.

.

Update: Added death on error.

Update2: Re AM's followup The BADSYMS filehandle is already closed. Replace with "BADSYMS.out" in the -z test.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re: Re: -z file test operator
by Anonymous Monk on Aug 30, 2001 at 18:19 UTC
    Hi, now I am using:
    close (BADSYMS); if (-z BADSYMS ) { unlink "BADSYMS.out" or die ("Cant delete BADSYMS.out"); print "hi"; } else { print "Bad symbols contained in BADSYMS.out\n"; }

    What happens now is when the file is zero or not zero, the if part is skipped, and it goes straight to the else. When the file is non-zero a message is returned:

    Stat on unopened file <BADSYMS> at test.pl line 317

    The filenames are assigned at the start of the script

    unless (open (BADSYMS, ">BADSYMS.out")) { die ("Can't open output file BADSYMS.out\n"); }

    This isn't in a loop as such, the script runs and the file maybe written to, if it isn't and therefore is empty, I want to delete it. If it is written to I want the print statement to output the name.

    Thanx, Martin

      Your problems are 1) you close the file handle then try to test it. 2) You can't unlink an file that has an open filehandle on many systems. This should be self explanatory code. $file is the FILE NAME. We open this file onto the FILE HANDLE called BAD. We can then read from the file through the filehandle.

      $file = "bad.out"; open BAD, $file or die "Oops can't open $file Perl says $!\n" # do stuff to BAD close BAD; if ( -s $file ) { # file has size } else { # file has zero size unlink $file or die "Can't unlink $file: $!\n"; }

      PS Get a login! cheers

      tachyon

      s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print