use of undef

Austin Schutz tex at
Mon Jun 11 17:29:05 CDT 2001

On Mon, Jun 11, 2001 at 02:31:36PM -0700, Tom Keller wrote:
> Hi all,
> I'm confused about the use of undef.
> I want to count the number of elements in a list until the first undefined value.
> I tried this:
> @array = (0, 1, 2,  , "next", "group");
> ELEMENTS: foreach $element (@array) {
>       $count++;
>       last ELEMENTS if $element eq undef;
> }
> It gives me the correct count, 3, and leaves the loop correctly, but I get a warning for each element.
> What am I missing?

	undef is an actual value and takes up a space in the array.
You can't test for it using eq, since that will try to do a string comparison.
undef is not the same thing as the defined string ''. Use defined() where
applicable. You should also take a look at exists() for testing whether or
not there is a given key in a hash.
	Try this:

@array = (0, 1, 2, undef , , "next", "group");
ELEMENTS: foreach $element (@array) {
  last ELEMENTS if ! defined( $element );
print $count;

	( I get 4, ymmv. :-) )


More information about the Pdx-pm-list mailing list