use of undef

Tom Phoenix rootbeer at
Mon Jun 11 18:37:14 CDT 2001

On Mon, 11 Jun 2001, Austin Schutz wrote:

> > @array = (0, 1, 2,  , "next", "group");

> @array = (0, 1, 2, undef , , "next", "group");

Note that the "empty element" between those two consecutive commas in both
cases is _not_ an undefined value. It's just a syntactic quirk that Perl
forgives extra commas in a list, if you want to think of it that way. So
the first line of code puts five elements into @array, while the second
supplies six.

> ELEMENTS: foreach $element (@array) {
>   $count++;
>   last ELEMENTS if ! defined( $element );
> }
> print $count;
> 	( I get 4, ymmv. :-) )

Of course, you're counting also the undefined element, because you
increment before you check whether it's defined or not. That's okay, but
the original request is ambiguous. If you want "the number of elements
before undef" and you're talking about the list (1, 2, 3), the answer
could either be three or zero, right? So this sub may or may not do what
is really wanted:

    sub number_before_undef {
	# Returns the number of elements found before an undef value 
	# in the parameter list. If there's no undef value, returns
	# undef.
	my $count = 0;
	foreach (@_) {
	    return $count if not defined $_;
	# There was no undef found, so....
	return undef;

    my @array = ("fred", , "barney", "wilma", (), "betty",
	"undef", "just kidding!", undef, 3, "fred",
	"wilma", "betty", 2..10, undef, "yes, again");

    my $num = number_before_undef @array;
    if (defined $num) {
	print "There were $num items before undef in the list.\n";
    } else {
	print "No undef found in that list.\n";

Hope this helps!

Tom Phoenix       Perl Training and Hacking       Esperanto
Randal Schwartz Case:

----- End forwarded message -----

More information about the Pdx-pm-list mailing list