Friday, May 27, 2011

defined and exists difference in perl

Perl has the defined and exists keywords that operate on hash elements.

$hash{'foo'} = 'bar';
print defined $hash{'foo'};      #  prints 1
print exists $hash{'foo'};       #  prints 1

For most purposes, they do the same thing. The one subtle difference
is when the hash value is the special "undefined" value:

$hash{'baz'} = undef;
print defined $hash{'baz'};      # doesn't print 1
print exists $hash{'baz'};       # prints 1

No comments: