禁止“开始失败——编译中止于”

发布于 2024-12-11 18:29:03 字数 803 浏览 0 评论 0原文

我有一个模块需要在 BEGIN 块中进行一些检查。这可以防止用户看到无用的消息(在编译阶段,在第二个 BEGIN 中看到)。

问题是,如果我死在 BEGIN 内,我抛出的消息就会被埋在后面 BEGIN 失败 - 编译中止于。不过,我更喜欢 die 而不是 exit 1,因为这样它就可以被捕获。我应该只使用 exit 1 还是可以采取一些措施来抑制此附加消息?

#!/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.";
}

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.";
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

五里雾 2024-12-18 18:29:03

当您死亡时,您将抛出一个在较早的调用级别捕获的异常。唯一能够从 BEGIN 块捕获 die 的处理程序是编译器,它会自动附加您不需要的错误字符串。

为了避免这种情况,您可以使用您找到的 exit 1 解决方案,也可以安装新的芯片处理程序:

# place this at the top of the BEGIN block before you try to die

local $SIG{__DIE__} = sub {warn @_; exit 1};

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};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文