perl function exists

The exists function in Perl is used to check if a given key exists in a hash or an array element exists in an array. Here are some examples:

my %hash = (a => 1, b => 2, c => 3);

if (exists $hash{a}) {
  print "Key 'a' exists in the hash\n";
}

if (!exists $hash{d}) {
  print "Key 'd' does not exist in the hash\n";
}
‮S‬ource:www.theitroad.com

In this example, the exists function is used to check if the hash %hash contains the key 'a'. The first if statement prints "Key 'a' exists in the hash" because the key 'a' does exist in the hash. The second if statement prints "Key 'd' does not exist in the hash" because the key 'd' does not exist in the hash.

Here is an example using an array:

my @array = (1, 2, 3, 4);

if (exists $array[0]) {
  print "Element 0 exists in the array\n";
}

if (!exists $array[4]) {
  print "Element 4 does not exist in the array\n";
}

In this example, the exists function is used to check if the array @array contains an element at index 0. The first if statement prints "Element 0 exists in the array" because there is an element at index 0. The second if statement prints "Element 4 does not exist in the array" because there is no element at index 4.

It's important to note that exists is different from checking if a key or element is defined. exists only checks if the key or element exists, regardless of its value. To check if a key or element is defined, you can use the defined function.