2

In a for loop I usually do this:

for my $i (0 .. 6){
###stuff to loop
}

Though, is it recognized as improper usage if I use $i multiple times? eg:

(These loops are purposely nested together)

for my $i (0 .. 6){
###some stuff
    for my $i (0 .. 30){
    ###double looped ...
    }
}
4
  • I would suggest using different variable names to if you have to use more then one index, it is easier to track what is occurring and probably more helpful in debugging if something does not work correctly. Commented Dec 1, 2013 at 7:57
  • Did you mean to make those for loop nested? Or is that just a typo? Commented Dec 1, 2013 at 8:00
  • @TLP It was on purpose, sorry for not clarifying that. Commented Dec 1, 2013 at 8:05
  • @Shortland You should use indentation. Commented Dec 1, 2013 at 8:07

1 Answer 1

8

It is quite possible to write code like that, using nested loops with the same name on the iterator, and it is what happens when you use the default variable $_. Whether you should do it is another question.

What happens is that the variables become localized.

for my $i (1 .. 2) {
    # $i == 1 or 2
    for my $i (3 .. 4) {
    # $i == 3 or 4
    }
    # $i returns to the old value 1 or 2
}

If you use the same variable name in a nested loop, you cannot access the loop iterator of the outer loop inside the inner loop. So in answer to your question, if not improper, it is rather impractical. And I assume that with less experienced programmers, it can lead to confusion, so in that sense, I would say it was not a good idea.

Sign up to request clarification or add additional context in comments.

1 Comment

They were purposely nested together, sorry for not clarifying that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.