I have a module which needs to do some checking in a BEGIN block. This prevents the user from seeing a useless message down the line (during compile phase, seen in second BEGIN here).
The problem is that if I die inside the BEGIN the message I throw gets buried behind
BEGIN failed--compilation aborted at
. However I prefer die
to exit 1
since it would then be trappable. Should I just use exit 1
or is there something I can do to suppress this additional message?
#!/usr/bin/env perl
use strict;
use warnings;
BEGIN {
my $message = "Useful message, helping the user prevent Horrible Death";
if ($ENV{AUTOMATED_TESTING}) {
# prevent CPANtesters from filling my mailbox
print $message;
exit 0;
} else {
## appends: BEGIN failed--compilation aborted at
## which obscures the useful message
die $message;
## this mechanism means that the error is not trappable
#print $message;
#exit 1;
}
}
BEGIN {
die "Horrible Death with useless message.";
}
When you die
you are throwing an exception that gets caught at an earlier call level. The only handler that will catch the die
from your BEGIN
block is the compiler, and that is automatically attaching the error string you don't want.
To avoid this, you can either use the exit 1
solution you found, or you can install a new die handler:
# place this at the top of the BEGIN block before you try to die
local $SIG{__DIE__} = sub {warn @_; exit 1};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With