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

The question is simple, but I suspect the answer may not be. I want to set $! to generate custom error messages from my packages and objects. I know this is possible with a Perl extension written in C, but I don’t want to do that. The main goal is to use a truly global variable to pass error data in. Right now I’m using $_, but I have to be careful to avoid other functions from overwriting it. Thanks.

Replies are listed 'Best First'.
Re: Special Variable Access
by BazB (Priest) on Jan 25, 2003 at 00:40 UTC

    Is over-writing $! a good idea?

    The errno values that pfaut(++) mentions are there for a reason.

    What is wrong with supplying your error message to die (or warn, or any of the Carp methods) in the normal way:

    die "Custom error messages are good!" if $condition;
    You don't have to include $! in your die statements, if you don't want to.

    Alternatively, you can install a __DIE__ handler to override the default behaviour of die:

    #!/usr/bin/perl use strict; use warnings; local $SIG{__DIE__} = sub { die scalar localtime(), " " , $_[0] }; die "Argh!";
    produces:
    Sat Jan 25 00:40:36 2003 Argh! at ./custom_die.pl line 8.

    If the information in this post is inaccurate, or just plain wrong, don't just downvote - please post explaining what's wrong.
    That way everyone learns.

Re: Special Variable Access
by pfaut (Priest) on Jan 25, 2003 at 00:32 UTC

    If the errors you are returning can be expressed as errno values, just assign the numeric value to $!. Things should work as expected.

    If you want to set error strings, try using $@ which is used by eval. Some CPAN modules (IO::Socket::INET for one) also use it to return error strings.

    --- print map { my ($m)=1<<hex($_)&11?' ':''; $m.=substr('AHJPacehklnorstu',hex($_),1) } split //,'2fde0abe76c36c914586c';