in reply to Re: -e and unlink
in thread -e and unlink

japhy's reply may be worth expanding on.

IF you don't care about reporting errors, then     unlink $filename; is sufficient.

IF you DO care about reporting errors (such as a failure to remove a file that your script lacks permission to remove), then you'll want to do something like:

if ( -e $filename ) { unlink($filename) or die "$filename: $!" }

Replies are listed 'Best First'.
Re: Re: Re: -e and unlink
by merlyn (Sage) on Mar 14, 2001 at 05:04 UTC
    But you can still avoid the -e test:
    unlink $filename or $! == 2 or die "Cannot unlink $filename: $!";
    On my system, "2" is the code for a missing file for unlink. If you don't mind the regex hit, you could also use:
    unlink $filename or $! =~ /no such/i or die "Cannot unlink: $filename: + $!";

    -- Randal L. Schwartz, Perl hacker


    update:

    This is actually faster than a separate test and unlink (one O/S call instead of two), and is less prone to race conditions. I'd actually scream at someone who did a -e/unlink pair instead of this in a security or performance related application.

        Note, the above note was clobbered by a bug. Please don't vote on it until it can be restored.

        I'd update the node itself, but I don't want to tamper with evidence. /:

                - tye (but my friends call me "Tye")