Perl version

Modules

  • ABCDE
  • FGHIL
  • MNOPS
  • TUX

exists

Perl 5 version 8.8 documentation
Recently read

exists

  • exists EXPR

    Given an expression that specifies a hash element or array element, returns true if the specified element in the hash or array has ever been initialized, even if the corresponding value is undefined. The element is not autovivified if it doesn't exist.

    1. print "Exists\n" if exists $hash{$key};
    2. print "Defined\n" if defined $hash{$key};
    3. print "True\n" if $hash{$key};
    4. print "Exists\n" if exists $array[$index];
    5. print "Defined\n" if defined $array[$index];
    6. print "True\n" if $array[$index];

    A hash or array element can be true only if it's defined, and defined if it exists, but the reverse doesn't necessarily hold true.

    Given an expression that specifies the name of a subroutine, returns true if the specified subroutine has ever been declared, even if it is undefined. Mentioning a subroutine name for exists or defined does not count as declaring it. Note that a subroutine which does not exist may still be callable: its package may have an AUTOLOAD method that makes it spring into existence the first time that it is called -- see perlsub.

    1. print "Exists\n" if exists &subroutine;
    2. print "Defined\n" if defined &subroutine;

    Note that the EXPR can be arbitrarily complicated as long as the final operation is a hash or array key lookup or subroutine name:

    1. if (exists $ref->{A}->{B}->{$key}) { }
    2. if (exists $hash{A}{B}{$key}) { }
    3. if (exists $ref->{A}->{B}->[$ix]) { }
    4. if (exists $hash{A}{B}[$ix]) { }
    5. if (exists &{$ref->{A}{B}{$key}}) { }

    Although the deepest nested array or hash will not spring into existence just because its existence was tested, any intervening ones will. Thus $ref->{"A"} and $ref->{"A"}->{"B"} will spring into existence due to the existence test for the $key element above. This happens anywhere the arrow operator is used, including even:

    1. undef $ref;
    2. if (exists $ref->{"Some key"}) { }
    3. print $ref; # prints HASH(0x80d3d5c)

    This surprising autovivification in what does not at first--or even second--glance appear to be an lvalue context may be fixed in a future release.

    See Pseudo-hashes: Using an array as a hash in perlref for specifics on how exists() acts when used on a pseudo-hash.

    Use of a subroutine call, rather than a subroutine name, as an argument to exists() is an error.

    1. exists ⊂ # OK
    2. exists &sub(); # Error