Reputation: 94349
In a Perl program I'm working on, the user can specify a Perl module to be loaded which is expected to define a couple (a variable number) of variables. The Perl program then processes these variables, basically treating the package as a plain hash except that the values are all in a namespace. Doing so works fine, i.e. this program prints '2':
use strict;
use warnings;
package P {
my $k1 = 'v1';
my $k2 = 'v2';
};
my $n = scalar keys %P::;
print "Number of entries: $n\n";
# print $P::x;
However, uncommenting the last line makes the program print '3'. I.e. the sheer mentioning of a variable in the package seems to add it to the symbol table.
Is there a way to get the symbol table for a package as it is defined, such that the symbol table consists of just two entries?
Upvotes: 3
Views: 244
Reputation: 118605
Package variables encountered at compile-time will be added to the stash at compile time. So your workarounds are to evaluate the stash in the compile phase
package P {
$k1 = 'v1';
$k2 = 'v2';
};
BEGIN {
my $n = scalar keys %P::;
print "Number of entries: $n\n"; # 2
}
print $P::x;
or to define other package variables at run-time
package P {
$k1 = 'v1';
$k2 = 'v2';
};
my $n = scalar keys %P::;
print "Number of entries: $n\n"; # 2
print eval '$P::x';
$n = scalar keys %P::;
print "Number of entries: $n\n"; # now 3
Upvotes: 5