what is the difference between the usageof exits and defined fuction in perl?

Hello, what is the difference between the usageof exits and defined fuction in perl? I would like to understand on which scenario one should be used and not the others. Please provide some example to understand it better. Thanks!
Who is Participating?

Improve company productivity with a Business Account.Sign Up

ozoConnect With a Mentor Commented:
print "Defined\n"   if defined $hash{key};
print "Exists\n"    if exists $hash{key};

print "Defined\n"   if defined $scalar;
eval 'print "Exists\n"    if exists $scalar';
print $@;

See also
perldoc -f exists
perldoc -f defined
wilcoxonConnect With a Mentor Commented:
To expand on ozo's example code...

exists only works on hashes and says if the key exists (in the example above $hash{key} exists but $hash{other} does not).  Put another way, it queries the %hash itself asking does "key" exist as a key in the hash?

Defined simply says if the value is defined or not (neither $hash{key} nor $hash{other} are defined in the above).  It will work on things other than a hash.  Put another way, for hashes, it asks is the specific value of $hash{key} defined?

One thing that surprised me a little that I just tested is that defined($hash{other}) does not auto-vivify (auto-magically create) $hash{other}.  In other words, defined($hash{other}) followed by exists($hash{other}) both return false (however either defined($hash{other}{sub}) or exists($hash{other}{sub}) will auto-vivify so exists($hash{other}) after either will return true).
As explained in the the Perl documentation cited above
exists also works on array elements and subroutine names
Interesting.  I still learn new things about perl.  I never knew (or forgot) that exists will work for array elements or subroutine names.  I can think of cases when it would be useful to test array elements but can't think of any time when it would have been useful for subroutine names (but I'm sure they exist in some use cases).
perldoc Errno
has an example of the use of exists on a subroutine name

the B module also uses it
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.