Reputation: 23
I am attempting to check a bunch of variables to ensure that they are defined. I thought I would put the variable names in an array and loop over the array checking if each variable was defined. However, as best I can understand it, the use of symbolic references for lexical variables (defined by "my") does not work.
Is there a way in Perl to check if a large number of lexical variables are defined without resorting to putting each variable name into a defined statement manually? It would seem to be better if I could create an array or something to hold the names of the variables whose defined status I wish to check.
Upvotes: 2
Views: 124
Reputation: 8532
It sounds like you need to rethink the structure of your code. Having a large number of lexical variables like that suggests a bad design - should they perhaps not live in a hash or an array? Then they could be iterated over much simpler.
Upvotes: 0
Reputation: 385657
Also put a ref to the var in the array.
my @vars = (
[ '$x', \$x ],
[ '$y', \$y ],
[ '$z', \$z ],
);
for (@vars) {
my ($name, $ref) = @$_;
print("$name is undefined\n") if !defined($$ref);
}
I don't see what's so hard about including a name when you include the variable. The alternative is to have PadWalker scan the internals. I wouldn't use that in production, but it can be useful in a debugging tool.
Upvotes: 2