in reply to To die or not to die

You could always check if the file exists before trying to open it, and use that to decide whether to open it for input or output. That way, you know that if it exists but you can't open it for input, the error is serious enough to warrent a die (or warn depending on your error handling).

if ( -e $file ) { open FH, $file or die "Failed: $! trying open existing $file\ +n"; # read it open FH, '>', $file or die "Failed: $! trying to re-open $file\n"; + } else { open FH, '>'.$file or die "Failed: $! trying to create new $file\ +n"; # do stuff }

This way, if you get out of the if/else, you know you have a file open for output ready for (re)writing.

It also means that you get a meaningful error msg if the file is read-only.


Nah! Your thinking of Simon Templar, originally played by Roger Moore and later by Ian Ogilvy

Replies are listed 'Best First'.
Re^2: To die or not to die
by Aristotle (Chancellor) on Oct 29, 2002 at 20:50 UTC
    It probably won't matter here, but that's a bad idea in general since you open up yourself to a race condition: the file might be created after the -e test but before the open by another process. You need an atomic operation:
    if (open FH, "<", $file) { # read it and do stuff open FH, ">", $file or die "Failed: $! trying to re-open $file\n"; } else { # do stuff open FH, ">", $file or die "Failed: $! trying to create new $file +\n"; }
    Also, use the three-argument form of open as I've said elsewhere in this thread.

    Makeshifts last the longest.