My Favorite Warnings: once

The Perl compiler wants to help us write clean code. One of the ways that it does this is to issue warnings when a global variable appears ony once: Name "main::Foo" used only once: possible typo at ...

The thing is, sometimes this is not an error. For example, we may want to refer to a global variable in another package, one that was not imported into our namespace.

I have seen various expedients used to avoid this warning in CPAN code. Something like $Foo::Bar = $Foo::Bar = 42; is fairly typical. Sometimes this strange-looking code is commented as to its purpose, others not.

Alternatively, you can use the pragma no warnings 'once'; to supress this warning. This seems to me the appropriate way to spell "I meant to do that!" under the circumstances:

{
    no warnings 'once';
    $Foo::Bar = 42;
}

Oddly, the relevant portion of perldoc perldiag does not mention this explicitly, though I suppose the annotation (W once) should be considered to imply it. On the other hand, it does explicitly mention inserting a second reference, which may be what gave rise to the code in the third paragraph ($Foo::Bar = $Foo::Bar = 42;.)

This is the first (and perhaps only) entry in a possible desultory series of blogs on the warnings pragma.

1 Comment

before I only know this warining dispaly for only declare variable... I don't connect them together

Leave a comment

About Tom Wyant

user-pic Fine Perl code for over 0.005 centuries.