Idiom #108 Determine if variable name is defined
Print the value of variable x, but only if x has been declared in this program.
This makes sense in some languages, not all of them. (Null values are not the point, rather the very existence of the variable.)
print $x; # compile error
print $x if $main::{x}; # prints $x if it was declared
use strict 'vars';
# or
use v5.11; # or higher
print $x if $main::{x}; # unavoidable compile error
By default, perl will automatically define variables when they are used. But you can check the symbol table to see if the variable exists. The default package name is main::, so this code checks the hash %main:: by doing a lookup for symbol 'x' using $main::{x}.
The pragma use strict 'vars' enforces explicit definition of variables before use. In addition, 'use VERSION' will enable strict if the version is v5.11 or higher. When in effect, undeclared variables cause a compile-time error.
The pragma use strict 'vars' enforces explicit definition of variables before use. In addition, 'use VERSION' will enable strict if the version is v5.11 or higher. When in effect, undeclared variables cause a compile-time error.