in reply to To die or not to die

You might want to write a generic reporting sub. I have a standard package of useful routines I use again and again in my programs and one of them is a subroutine that prints to STDOUT allows you to exit or not exit as you see fit.

Ie, open(INPUT, "<input.txt") || NoGo(error=>"Could not open file input.txt for reading", exit=>1);

That way you can report errors to yourself or the user and terminate the program if necessary with a minimum of hassle. This is best if you are only worried about success or failure and not the exact cause.

SpaceAce

Replies are listed 'Best First'.
Re: Re: To die or not to die
by bprew (Monk) on Oct 28, 2002 at 20:46 UTC

    If you didn't want to die, and didn't want to use merlyn's example, you could always "warn" instead of die... ex

    open(INPUT, "input.txt") or warn("Could not open file input.txt $!\n");

    Also, note that on the open(), the file is "input.txt" and not ">input.txt" as this will open the file for writing, destroying anything that might already be in the file and would only die or warn if the file could not be created (low disk space, permissions, etc).

    One last thing, what's the difference between or and || in die or warn statements? I know one is numeric and the other string, but as far as usage in this example, is there a difference or purely syntatic sugar?

    Thanks
    --
    Ben
    "Naked I came from my mother's womb, and naked I will depart."

      you could always "warn" instead of die
      ... except that you'd then be warning even on "expected" conditions. Earlier in this thread it was said that having no config file was a reasonable and expected condition.

      If you have warnings disabled, you could do:

      open F, "config.txt" or $! !~ /no such file/i or die "config.txt error +: $!"; ... process F ...; close F;
      Warnings will have to be turned off because you'll be doing I/O on a closed filehandle. My other code posted earlier doesn't have that issue.

      -- Randal L. Schwartz, Perl hacker
      Be sure to read my standard disclaimer if this is a reply.