如何在 Perl 中将某些特定的鲤鱼更改为黄花鱼?
我试图捕捉鲤鱼警告:
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";
I tried to catch a carp-warning:
carp "$start is > $end" if (warnings::enabled()); )
with eval {} but it didn't work, so I looked in the eval
documentation and I discovered, that eval
catches only syntax-errors, run-time-errors or executed die-statements.
How could I catch a carp warning?
#!/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";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据您的评论,我的理解是您希望将
carp
设为致命警告。如果可以接受将目标包中的所有
carp
警告变成致命错误,那么您可以对carp
进行猴子补丁。Carping包:
主程序:
如果想将monkey补丁限制在动态范围内,可以使用
local
:Based on your comments, my understanding is that you would like to make
carp
into a fatal warning.If it is acceptable to make all
carp
warnings in your target package into fatal errors you can monkey-patchcarp
.Carping Package:
Main program:
If you want to limit the monkey patch to a dynamic scope, you can use
local
:carp 不会死,只是打印一个警告,所以 eval 或其他什么都没有什么可捕获的。但是,您可以在本地覆盖警告处理程序,以防止警告发送到 stderr:
输出:
在几乎所有情况下,您应该更愿意修复鲤鱼的原因。
carp does not die but just prints a warning, so there's nothing to catch with eval or whatever. You can, however, overwrite the warn handler locally to prevent the warning from being sent to stderr:
Output:
In almost all cases you should prefer fixing the cause of the carp instead.