First off, "undefined array" is not a useful concept (in Perl anyway). In Perl an array can be empty or not, but not undefined. However, remember that a Perl array is an array of scalar elements and a scalar may have the value 'undef'.

Using @array in a scalar context (in a conditional statement for example) returns a number which is the number of elements in the array. Note however that that is a number so the numeric comparison operators (==, != <, ...) are appropriate, not the string comparison operators (eq, ne, lt, ...).

Now, to address the warning in your code. Consider:

use strict; use warnings; my @array; print "\@array contains ", scalar @array, " elements\n"; print for @array; @array = undef; print "\@array now contains ", scalar @array, " element\n"; for my $index (0 .. $#array) { print "Element at $index: ", (defined $_ ? "'$_'" : "undefined"), +"\n" } @array = (); print "\@array contains ", scalar @array, " elements\n";

Prints:

@array contains 0 elements @array now contains 1 element Element at 0: undefined @array contains 0 elements

Do you see that the assignment @array = undef has almost exactly the opposite effect to the one I suspect you expected? It populates the array with one element which has the value undef! If you want to empty an array assign the empty list () to it.

True laziness is hard work

In reply to Re: Question about foreach/iterating/verifying an undefined array by GrandFather
in thread Question about foreach/iterating/verifying an undefined array by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.