Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

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

if(@$foo) print($foo);
$x = 'foo';

if (isset($x)) {
    echo $x;
}
int x = 42;

void printIfDefined(alias name)()
{
    import std.stdio: writeln;
    static if( __traits(compiles, writeln(mixin(name))))
        writeln(mixin(name));
}

void main(string[] args)
{
    printIfDefined!"x";
    printIfDefined!"Foo.bar";
}
import std.stdio;
static if (is(typeof(x = x.init)))
    writeln(x);
implicit none

print *,x
if (typeof x !== 'undefined') {
    console.log(x);
}
try {
	console.log(x);
} catch (e) {
	if (!e instanceof ReferenceError) {
		throw e;
	}
}
import static java.lang.System.out;
import java.lang.reflect.Field;
try {
    Field f = getClass().getDeclaredField("x");
    out.println(f.get(this));
} catch (NoSuchFieldException e) {

} catch (IllegalAccessException e) {

}
if x then print(x) end
{$if DECLARED(x)}
writeln(x);
{$endif}
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

try:
    x
except NameError:
    print("does not exist")
if 'x' in locals():
	print(x)
puts x if defined?(x)

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