1

我试图捕捉鲤鱼警告:

 carp "$start is > $end" if (warnings::enabled()); ) 

使用eval {}但它不起作用,所以我查看了eval文档,发现eval它只捕获语法错误、运行时错误或执行的死亡语句。

我怎么能抓住鲤鱼警告?

#!/usr/bin/env perl
use warnings;
use strict;
use 5.012;
use List::Util qw(max min);
use Number::Range;

my @array;
my $max = 20;
print "Input (max $max): ";
my $in = <>;

$in =~ s/\s+//g;
$in =~ s/(?<=\d)-/../g;

eval {
    my $range = new Number::Range( $in );
    @array = sort { $a <=> $b } $range->range;
};
if ( $@ =~ /\d+ is > \d+/ ) { die $@ }; # catch the carp-warning doesn't work 

die "Input greater than $max not allowed $!" if defined $max and max( @array ) > $max;
die "Input '0' or less not allowed $!" if min( @array ) < 1;
say "@array";
4

2 回答 2

3

根据您的评论,我的理解是您想carp发出致命警告。

如果可以接受将carp目标包中的所有警告变成致命错误,则可以使用 monkey-patch carp

吹毛求疵套餐:

package Foo;
use Carp;

sub annoying_sub {
    carp "Whine whine whine";
}

主程序:

use Foo;

*Foo::carp = \&Foo::croak;

Foo::annoying_sub();

如果要将猴子补丁限制在动态范围内,可以使用local

use Foo;

Foo::annoying_sub();  # non-fatal

{   local *Foo::carp = \&Foo::croak;
    Foo::annoying_sub();  # Fatal
}
于 2010-05-12T16:06:01.323 回答
3

carp 不会死,只是打印一个警告,所以没有什么可以用 eval 或其他东西捕捉到的。但是,您可以在本地覆盖警告处理程序以防止将警告发送到 stderr:

#!/usr/bin/env perl

use warnings;
use strict;

use Carp;

carp "Oh noes!";

{
    local $SIG{__WARN__} = sub {
        my ($warning) = @_;

        # Replace some warnings:
        if($warning =~ /replaceme/) {
            print STDERR "My new warning.\n";
        }
        else {
            print STDERR $warning;
        }

        # Or do nothing to silence the warning.
    };

    carp "Wh00t!";
    carp "replaceme";
}

carp "Arrgh!";

输出:

Oh noes! at foo.pl line 8
Wh00t! at foo.pl line 25
My new warning.
Arrgh! at foo.pl line 29

在几乎所有情况下,您应该更喜欢修复鲤鱼的原因。

于 2010-05-12T10:56:02.877 回答