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:
- Even if an element is undefined, it can still exist.
- Setting an element to undef brings it into existence, but checking whether it's defined does not.
- 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.
- 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.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.