Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

for loop exits incorrectly

for loop exits incorrectly

for loop exits incorrectly


Platform is perl 5.005.03 on AIX 4.1.5.

I wrote a for loop incorrectly and it almost worked, which caused me some grief. Why does this loop exit?

I meant to write
for ($sl = length($s), $sl < $l, $sl = length($s)) {

but what I wrote was

$s = "12345678";
$l = 14;
for ($sl = length($s), $sl < $l,) {
$s .= $s; # double the length of $s
$s = substr($s, 0, $l);

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?

( I know, I really should have just written
while (length($s) < $l) { $s .=$s }

I must have been more tired than usual that day. But the question still remains, why does the malformed for loop exit? )

- Kai.

RE: for loop exits incorrectly


Surprising to me that "for ($sl = length($s), $sl < $l,)" ran at all. <smile>

Wierdest question I've seen in a while.

No idea of the answer, but please keep asking the interesting questions.

Robherc might know - Rob?

And you're right - you should have written "while (length($s) < $l) { $s .=$s }", much more readable!


Mike Lacey
Cargill's Corporate Web Site

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close