[Israel.pm] C style for loop

Mikhael Goikhman migo at freeshell.org
Sun Mar 11 07:14:21 PDT 2012


This reply was written on Mar 8, but for some reason it was not
sent, so I am resending it.

On 08 Mar 2012 15:13:12 -0800, Roman M. Parparov wrote:
> 
> On 3/8/12 2:37 PM, sawyer x wrote:
> >
> > Writing a C-style for() loop does not give you the index value if
> > you define it using my().
> >     for ( my $i = 0; $i < 10; $i++ ) {...}
> 
> But if I my() the variable outside the loop, then in C-style it is
> defined, while in range-style it is not.

Yes. "for $i (42) {...}" is even the same as "for my $i (42) {...}",
that IMHO was a questionable language decision (less flexibility).

> > No reason not to move on to a more readable (and in calculated
> > instances even FASTER) range-style for() loop instead. :)

This statement is in the same league as "CGI.pm must die". :)

As mentioned by Roman, the range-style "for" can't work in several
cases (negative or non-linear step; catching the last loop index).

Another common task is to quickly parse an array with mixed control
elements. Like ("arg1", "--single-value-option", "value",
"--flag-option", "--bi-value-option", "value1", "value2", "arg2").

If you insist to do this with the range-style "for", you need to
introduce state variables to remember multi-element options resulting
in a less readable code. This is redundant if you can freely advance
the loop index inline:

	if ($params[$i] eq '--single-value-option') {
		$params[++$i]  # do something with the value
	}

The actual real-life examples can be even more interesting. i.e.
parsing binary formats, traversing linked lists and more.

Personally I don't use the C-style "for" too, even in all these cases
mentioned so far, because I prefer "while" that is as powerful. But
saying that the range-style "for" is *the* solution is just not true.

BTW, Ran in his talk uses "while" for simple loops too:

my $i; while ($i++ < $STAR_COUNT) {
	...;
}

Regards,
Mikhael.

-- 
perl -le'print$,.=chr(64+hex),-8x(16+$;--)for+split//,d9b815c07f9b8d1e0'


More information about the Perl mailing list