Friday, May 27, 2011

Difference Between 'defined' and 'exists' in Perl

# Initialize a hash key 'foo' with a standard string value
$hash{'foo'} = 'bar';

# 'defined' checks if the value is something other than undef. 
# Since 'bar' is a valid string, it evaluates to true.
print defined $hash{'foo'};      # prints 1

# 'exists' checks if the key 'foo' is present in the hash, regardless of its value.
# Since we created the key above, it evaluates to true.
print exists $hash{'foo'};       # prints 1


# The subtle difference appears when a key is explicitly set to the 'undef' value:
$hash{'baz'} = undef;

# 'defined' evaluates the VALUE. Since the value is undef, this returns false.
print defined $hash{'baz'};      # doesn't print 1 (returns false/empty string)

# 'exists' evaluates the KEY. The key 'baz' has been created in the hash, 
# so it exists, even though its assigned value is undefined.
print exists $hash{'baz'};       # prints 1

No comments: