Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

for loop exits incorrectly

Status
Not open for further replies.

kaih

Programmer
Dec 7, 1999
26
US
<br>
Platform is perl 5.005.03 on AIX 4.1.5.<br>
<br>
I wrote a for loop incorrectly and it almost worked, which caused me some grief. Why does this loop exit?<br>
<br>
I meant to write <br>
for ($sl = length($s), $sl &lt; $l, $sl = length($s)) {<br>
<br>
but what I wrote was<br>
<br>
$s = &quot;12345678&quot;;<br>
$l = 14;<br>
for ($sl = length($s), $sl &lt; $l,) {<br>
$s .= $s; # double the length of $s<br>
}<br>
$s = substr($s, 0, $l);<br>
<br>
The intent is to create a string of length $l, starting from some arbitrary string. As written, the loop always runs twice, then exits. That is correct behavior as long as the initial length of $s is more than 1/2 $l and less than $l. But if any of those values change then the loop still runs twice then exits. Why?<br>
<br>
<br>
( I know, I really should have just written<br>
while (length($s) &lt; $l) { $s .=$s }<br>
<br>
I must have been more tired than usual that day. But the question still remains, why does the malformed for loop exit? )<br>
<br>
Thanks!<br>
- Kai.<br>

 
Kai,<br>
<br>
Surprising to me that &quot;for ($sl = length($s), $sl &lt; $l,)&quot; ran at all. &lt;smile&gt;<br>
<br>
Wierdest question I've seen in a while.<br>
<br>
No idea of the answer, but please keep asking the interesting questions.<br>
<br>
Robherc might know - Rob?<br>
<br>
And you're right - you should have written &quot;while (length($s) &lt; $l) { $s .=$s }&quot;, much more readable!<br>
<br>
Mike<br>
<p>Mike Lacey<br><a href=mailto:Mike_Lacey@Cargill.Com>Mike_Lacey@Cargill.Com</a><br><a href= Cargill's Corporate Web Site</a><br>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top