What is defined vs exists in Perl?

In Perl, the functions defined and exists are used to check for the presence of values in different contexts. Understanding how and when to use them is crucial for effective programming.

defined is used to determine if a scalar variable has been assigned any value, including an empty string or zero. It returns true if the variable is defined, and false if it is not.

exists, on the other hand, checks for the existence of a key in a hash. It returns true if the key is present, regardless of the value associated with that key (including undefined).

Example


my $var;
my %hash = (key1 => 'value1', key2 => undef);

if (defined $var) {
    print '$var is defined';
} else {
    print '$var is not defined';  # This will print
}

if (exists $hash{'key1'}) {
    print 'key1 exists in the hash';  # This will print
}

if (exists $hash{'key2'}) {
    print 'key2 exists in the hash';  # This will also print, even though its value is undef
}
    

keywords: Perl defined exists programming hash scalar