Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should use warnings; go last?

Tags:

warnings

perl

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?

like image 248
Chas. Owens Avatar asked Jul 28 '16 14:07

Chas. Owens


1 Answers

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. Edit The bug was fixed in v5.27.6.

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.
like image 97
Borodin Avatar answered Sep 28 '22 03:09

Borodin