in reply to Re: Unlinking a file when the file doesnt exist
in thread Unlinking a file when the file doesnt exist

Unfortunately, $! is garbage in that example. It would only be meaningful if stat (via -e) failed. One definitely cannot count on it having any info about an unlink error.

I recommend

for my $file (qw(files.txt data.txt)) { unlink($file) or $!{ENOENT} or die("Unable to unlink '$file': $!"); }

Or if one wants to clean up as many files as possible even if some can't be deleted,

my $success = 1; for my $file (qw(files.txt data.txt)) { if (!unlink($file) && !$!{ENOENT}) { warn("Unable to unlink '$file': $!"); $success = 0; } } die("Unable to cleanup") if !$success;

Replies are listed 'Best First'.
Re^3: Unlinking a file when the file doesnt exist
by moritz (Cardinal) on Mar 22, 2011 at 21:19 UTC
    Unfortunately, $! is garbage in that example.

    It contained the right value when I tried it. Is that platform (or perl version) dependent?

      It may have the right value if you're lucky. stat is free to change it, and you can reach the die even if unlink was successful.

Re^3: Unlinking a file when the file doesnt exist
by Gulliver (Monk) on Mar 23, 2011 at 15:12 UTC
    Unfortunately, $! is garbage in that example.

    From unlink:

    Deletes a list of files. On success, it returns the number of files it successfully deleted. On failure, it returns false and sets $! (errno):

    One of the examples at the perldoc page for unlink shows using $! with warn() in a foreach loop. Why shouldn't $! be used in this case?

      I didn't say anything that contradicts that. It's perfectly fine to use $! immediately after unlink returns an error as I showed in the very post you quoted.

      In moritz's code, $! isn't being used immediately after unlink returns an error. In decreasing likeliness of occurrence,

      • It's sometimes used after stat (-e) successfully returns false. (Can change $!.)
      • It's sometimes used after stat (-e) returns an error. (Always sets $!.)
      • It's sometimes used after unlink returns success. (!!!)