Chas. Owens Chas. Owens - 4 months ago 11
Perl Question

Why should use warnings; go last?

I vaguely recall that the

warnings
pragma should go last in the list of us modules being loaded with
use
. I also vaguely remember that it has something to do with modules registering their own warning categories, but I can't reproduce any problems. Can someone point to a relevant article or show an example where the placement of the
warnings
pragma makes a difference?

Answer

This may be what you're referring to. Either way it's something to be aware of and I'm submitting it as a bug

My/Warnings.pm

package My::Warnings;

use warnings::register;

sub test {
    warnings::warnif 'This is my warning';
}

1;

main.pl

use strict;
use feature 'switch';

use warnings 'all';

use My::Warnings;

print undef;

given (1) { }

My::Warnings::test();

As expected, this will output

given is experimental at E:\Perl\source\main.pl line 10.
Use of uninitialized value in print at E:\Perl\source\main.pl line 8.
This is my warning at E:\Perl\source\main.pl line 12.

However, if any warnings category is disabled, it will also disable the custom category. Like this

use strict;
use feature 'switch';

use warnings 'all';
no warnings 'experimental';

use My::Warnings;

print undef;

given (1) { }

My::Warnings::test();

This outputs just

Use of uninitialized value in print at E:\Perl\source\main.pl line 9.

and it seems to be necessary to enable warnings after the use My::Warnings to get them to perform

use strict;
use feature 'switch';

use My::Warnings;

use warnings 'all';
no warnings 'experimental';

print undef;

given (1) { }

My::Warnings::test();

Produces

Use of uninitialized value in print at E:\Perl\source\main.pl line 9.
This is my warning at E:\Perl\source\main.pl line 13.



Update

What's more, reenabling the category that switched off the custom warnings leaves them disabled

Something like this

use strict;
use feature 'switch';

use warnings 'all';
no warnings 'experimental';
use warnings 'experimental';

use My::Warnings;

print undef;

given (1) { }

My::Warnings::test();

prints just

given is experimental at E:\Perl\source\main.pl line 12.
Use of uninitialized value in print at E:\Perl\source\main.pl line 10.