1. Perl
  2. builtin functions
  3. here

exists function - check the existence of the hash key

You can use the exists function to check the existence of hash key.

# Hash key existence check
my $is_exists = exists $hash{$key};

To check if the key called age exists, do the following.

# Make sure the key age exists
my %person = (name =>'Ken', age => 1);
my $is_exists = exists $person{age};

In the case of hash reference, you can do the following:

# Confirm the existence of the key. For hash reference.
my $person = {name =>'Ken', age => 1};
my $is_exists = exists $person->{age};

Difference from defined function

A similar function is defined function. The exists function checks for the existence of a hash key, while the defined function is used to check if a value is defined.

my $defined = defined $person{age};

Example program

This is an example to check the exsitence of hash elements with the exists function.

use strict;
use warnings;
use Data::Dumper;

# Student math scores
my%math_scores = (
  Aiko => 89,
  Kenta => 0,
  Taro => undef
);

print Dumper \%math_scores;
print "\n";

# 1: exists function that confirms the existence of the key
print "1: Confirm the existence of the key\n";
for my $key (qw/Aiko Kenta Taro Masao/) {
  if (exists $math_scores{$key}) {
    print "\$math_scores{$key} exists.\n";
  }
  else {
    print "\$math_scores{$key} does not exist.\n";
  }
}

Output

%math_scores = (
                 'Aiko' => 89,
                 'Kenta' => 0,
                 'Taro' => undef
               );

# 1: Confirm the existence of the key
$math_scores{Aiko} exists.
$math_scores{Kenta} exists.
$math_scores{Taro} exists.
$math_scores{Masao} does not exist.

Related Informatrion