Logo

Programming-Idioms

  • JS
  • Dart
  • Perl

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.)

no strict 'vars';  # the default
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.
try {
	console.log(x);
} catch (e) {
	if (!e instanceof ReferenceError) {
		throw e;
	}
}
if (typeof x !== 'undefined') {
    console.log(x);
}

However if x has previously been declared and set to undefined, this will not print x even though x has been declared.
import std.stdio;
static if (is(typeof(x = x.init)))
    writeln(x);

We test, at compile-time, if an assignExpression with x as lhs would compile, if so we use it.

This technic is sometimes used in template constraints, but rather to test if an operation would be accepted on an argument.

New implementation...
< >
programming-idioms.org