Saturday, July 9, 2011

Perl Hash Functions: When to Use exists vs. defined

Understanding the Difference Between exists and defined in Perl

The Core Difference

  • defined checks the value of the variable (i.e., it verifies if the value is something other than undef).

  • exists checks if the variable or hash key has been previously declared or initialized, regardless of its actual value.

Code Examples

Scenario 1: Key is initialized with undef

Perl
$hash{$key} = undef;

exists  $hash{$key};  # TRUE (The key was declared)
defined $hash{$key};  # FALSE (The value is undef)
$hash{$key};          # FALSE

Scenario 2: Key is initialized with a value (0)

Perl
$hash{$key} = 0;

exists  $hash{$key};  # TRUE (The key was declared)
defined $hash{$key};  # TRUE (The value is defined as 0)
$hash{$key};          # FALSE (0 evaluates to false)

Scenario 3: Key was never initialized
Perl
exists $hash{$foo};   # FALSE (The key '$foo' was never declared)

No comments: