Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Perl's foreach loop will iterate over a list, assigning each value to $_. But if another variable is provided, it assigns the list elements to that variable instead. According to the perlsyn manpage, the foreach loop may be invoked with the foreach keyword or the for keyword. The foreach loop always localizes its iteration variable. This , which means the iteration variable does not preserve its value after the loop terminates. This can lead to surprising results if not accounted for. Consequently, it is recommended that the variable in a foreach loop be prefixed with my to make it explicit that the variable is private to the loop. And it is required that the variable not be read after the loop terminates.

...

However, the loop treats the iteration variable $value as local. So when it exits the list, $value regains the value it had before the loop. Since Because it was uninitialized before the loop, it therefore remains undefined afterwards, and the final print statement prints {{ is even}}:

Code Block
 is even.

Compliant Solution (Expanded Loop)

This compliant solution correctly prints 2 is even. It accomplishes this result by moving the print statement inside the loop , and therefore never refers to $value outside the loop.

...

Tool

Diagnostic

Perl::Critic

Variables::RequireLexicalLoopIterators

Bibliography

...

...

"Iterator Variables," p. 105
[

...

...

...

 

 

...

Image Modified Image Modified Image Modified