René Nyffenegger René Nyffenegger -4 years ago 106
Perl Question

Why does Perl not warn if using an undeclared variable in another namespace - and how can I be warned about this?

I am using

in my Perl scripts to be notified if I am using undeclared variables. Thus, the interpreter will warn that
is undeclared in the following scriptlet:

use warnings;
use strict;

$foo = 'bar';
print ($foo);

However, if I use an undeclared variable in another namespace, I am not warned. The following scriptlet runs without warning whatsoever.

use warnings;
use strict;

$BAR::foo = 'bar';
print ($BAR::foo);

Why is this difference?

Since I have lost quite some time figuring out exactly this problem, albeit in a much larger context, I am wondering if it is possible to make Perl me warn about using undeclared variables in other namespaces, too.

Answer Source

When you fully specify the namespace in which a variable belongs, perl assumes you know what you are doing. See perldoc strict:

strict vars

This generates a compile-time error if you access a variable that was neither explicitly declared (using any of my, our, state, or use vars) nor fully qualified.

I don't think there is a way to detect that you have specified a non-existent variable $BAR::foo. However, if the BAR package is under your control, you can avoid using package variables in the first place by mediating access to the state of foo using accessors, and hiding the variable from other modules.

The answer to problems created by using global variables is not to use global variables.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download