Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress "BEGIN failed--compilation aborted at"

Tags:

perl

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.";
}
like image 929
Joel Berger Avatar asked Oct 26 '11 14:10

Joel Berger


1 Answers

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};
like image 139
Eric Strom Avatar answered Oct 13 '22 13:10

Eric Strom