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
dieyou are throwing an exception that gets caught at an earlier call level. The only handler that will catch thediefrom yourBEGINblock is the compiler, and that is automatically attaching the error string you don’t want.To avoid this, you can either use the
exit 1solution you found, or you can install a new die handler: