Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Is it possible to check if an item in array exists like this:
if (-e $exp[12]) {
do something
}
If this won't work, how else should I do it? I don't like to run a subroutine on a element that doesn't exist!

Please help!

Replies are listed 'Best First'.
Re: Existing items
by echosilex (Acolyte) on Nov 16, 2002 at 04:23 UTC
    -e is used for checking to see if a file exists. I suggest using exists in place of -e, as exists is used specifically for checking the existence of elements of hashes or arrays.
Re: Existing items
by Ryszard (Priest) on Nov 16, 2002 at 08:46 UTC
    if (defined $exp[12]){ print $exp[12] }

    More to the point, why didnt you just try it...?

Re: Existing items
by Dr. Mu (Hermit) on Nov 17, 2002 at 04:22 UTC
    Just as with hashes, there's a clear distinction between whether an array element exists and whether it's defined. It can exist, but be undefined, as the following code illustrates:
    $exp[12] = undef; printf "%d,%d,%d,%d\n", exists $exp[11], exists $exp[12], exists $exp[ +13], scalar @exp; printf "%d,%d,%d,%d\n", defined $exp[11], defined $exp[12], defined $e +xp[13], scalar @exp;
    This prints:
    0,1,0,13 0,0,0,13
    This code illustrates a several things:
    1. Even if an element is undefined, it can still exist.
    2. Setting an element to undef brings it into existence, but checking whether it's defined does not.
    3. Just because an array element n exists, doesn't mean that all prior elements (0 .. n-1) also exist. If the array is sparsely populated, Perl keeps track of that fact.
    4. The size of an array, given by the scalar function, is not the number of elements that exist, but rather one plus the highest index of those existing elements.
    So to answer your question, if you're really interested in whether an array element exists, use the exists function, not defined.