tags:

views:

79

answers:

1

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 and 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?

+10  A: 

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.

hobbs
You could wrap it in a pointless sub. `sub bail{ use warnings FATAL => all; sub{warnings::warn('DANGER')}->() }`
Brad Gilbert
@hobbs: you've got it. the subs in the warnings package are intended for module developers, not as some kind of super warn().
ysth
It's not a bug, it's a (evil subtlety you say) feature <g>. Thanks for the explanation.
lexu
Thanks for the explanation hobbs!
Josh McAdams

related questions