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

When using the OPEN command to read a file, such as:
open (ARCHIVE1, ">>/directory/myfile") || die "File Not Found";

if the file is not found is there a way to have the program execute a specific subrotine instead of simply printing "File Not Found" to the screen?

Thanks in advance for for any adivce.

Replies are listed 'Best First'.
Re: Doing more than printing "File Not Found" with a die command
by Fletch (Bishop) on Aug 26, 2004 at 18:34 UTC

    Or if you want to do more than just one statement but don't want to dedicate a whole sub to error handling:

    unless( open( ARCHIVE, ">>blah" ) ) { warn "Aiieeeee, can't append to blah!\n"; $no_archive = 1; update_fleezle( -42 ); open( ARCHIVE, ">&STDOUT" ) or die "Can't dup STDOUT: $!\n"; }
Re: Doing more than printing "File Not Found" with a die command
by davido (Cardinal) on Aug 26, 2004 at 19:18 UTC

    Other error handling techniques involve still throwing the die, but trapping the event in an eval. Or, have a look at the Carp module, which will also allow you to supply an error-handler to gracefully recover (or terminate) from exceptions thrown with die.

    Also take note that "File not found" isn't the only reason open may fail. Rather than using such a specific statement of death, you might rewrite it as such:

    die "Couldn't open $filename for input:\n$!";

    That last little bit, the $! causes die to print what the operating system considers to be the real issue causing open to fail.


    Dave

Re: Doing more than printing "File Not Found" with a die command
by dragonchild (Archbishop) on Aug 26, 2004 at 18:25 UTC
    open( ARCHIVE1, ">>/directory/myfile" ) || my_sub();

    Or, am I missing something?

    ------
    We are the carpenters and bricklayers of the Information Age.

    Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose

    I shouldn't have to say this, but any code, unless otherwise stated, is untested

Re: Doing more than printing "File Not Found" with a die command
by eieio (Pilgrim) on Aug 26, 2004 at 18:28 UTC
    open( ARCHIVE1, ">>/directory/myfile") or mySpecificSubroutine();
    If open fails, it will return the undefined value at which point the whatever is on the right side of the "or" will be evaluated.