开发者

warnings::warn and FATAL categories in Perl

I must be understanding the warnings documentation wrong. The way I read it, this code:

use warnings;
use warnings FATAL => 'all';
warnings::warn('numeric', 'blarg');
print "finished\n";

Should print the 'blarg' warning an开发者_开发技巧d die since I've asked for all warnings to be fatal. However, when I run the code I get:

$> /opt/local/bin/perl x.pl 
blarg at x.pl line 3
finished

Can somone help me understand why I can't get warn to die?


Okay. This is ugly. I had a post half-prepared explaining this as a bug in warnings, and then I realized it's not, it's just a really evil subtlety in the way warnings works.

Warnings starts looking for a relevant stack frame to get the warning bits from in warnings::warn's caller's caller. The idea is that you're writing some module and you use warnings::warn or warnings::warnif in your functions, and whether or not the warning is printed (or fatal) depends on the use warnings setting in scope in the code that uses your module. There's no option provided to have it start at caller(1) instead of caller(2), so the effect you want isn't possible.

An example of code that does work (and demonstrates how this interface was expected to be used by whoever wrote it):

package Foo;
require warnings;

sub bail {
  warnings::warnif('numeric', "You fool! You divided by zero!");
}

package main;
use warnings FATAL => all;

Foo::bail();
print "Will never be reached\n";

And you can't defeat the way it works by just adding another level of subroutines, because it takes the flags from the first caller that's in a different package from the caller of warn/warnif/enable/etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜