[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

[MacPerl] While versus foreach



Something just came up which I thought I'd pass along to
everyone.  I usually use the WHILE statement when going
through an array.  This bit me today.  Another programmer
here suggested I use the FOREACH statement instead of the
WHILE statement and that cleared up my problem.  But I
thought I'd say something about this to the list.  :-)  I
know it's not a MacPerl specific problem but what-the-hay!
It might help someone (like my join/split problem before).

Here is an example:

#!perl
	@theList = ();
	$theList[++$#theList] = "A string";
	$theList[++$#theList] = "A string";
	$theList[++$#theList] = "A string";
	$theList[++$#theList] = "A string";
	$theList[++$#theList] = "A string";
	$theList[++$#theList] = "A string";
	$theList[++$#theList] = "A string";
	$theList[++$#theList] = "A string";
	$theList[++$#theList] = "A string";
	$theList[++$#theList] = "A string";
	while( @theList ){
		print "$_\n";
		}

	foreach( @theList ){
		print "$_\n";
		}
	exit( 0 );

What might or could happen with the WHILE loop is that it
will get caught in an endless loop.  This is because so
long as there is something in the variable, it will
register as TRUE to the WHILE statement.  Since nothing is
ever done to the variable to remove entries, the loop
executes forever.

I know - "no duh" to some people.  But I've been using the
WHILE loop set-up for quite a while without this biting
me.  Used up all of the swap space on the computer though
today.  :-/  So this is a sporadic thing in Perl.  Anyone
have any idea why _some_ of the time it works and _some_ of
the time it doesn't?  (ie: Why does it only not work
sporadically?)

PS: If you want to see an actual example (instead of the
above) I will be happy to send it to you.


***** Want to unsubscribe from this list?
***** Send mail with body "unsubscribe" to mac-perl-request@iis.ee.ethz.ch