我试着去抓一条鲤鱼-警告:
carp "$start is > $end" if (warnings::enabled()); ) 使用eval {},但它不起作用,所以我查看了eval文档,我发现eval只捕获语法错误、运行时错误或执行的die语句。
我怎么才能捕捉到鲤鱼的警告呢?
#!/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";发布于 2010-05-13 00:06:01
根据你的评论,我的理解是你想把carp变成一个致命的警告。
如果将目标包中的所有carp警告都变成致命错误是可以接受的,那么您可以对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-12 18:56:03
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在几乎所有的情况下,你应该倾向于修复鲤鱼的原因。
https://stackoverflow.com/questions/2817750
复制相似问题