我试图捕捉鲤鱼警告:
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";
答案 0 :(得分:3)
鲤鱼不会死,但只是打印一个警告,所以没有什么可以捕获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
在几乎所有情况下,你都应该更喜欢修理鲤鱼的原因。
答案 1 :(得分:3)
根据您的评论,我的理解是您希望carp
成为致命的警告。
如果可以将目标包中的所有carp
警告设置为致命错误,则可以修补carp
。
Carping Package:
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
}