The for loop behaves differently depending on how the variable $i is declared. Consider the following two programs -
#!/usr/local/bin/perl -w #!/usr/local/bin/perl -w use strict; use strict; my $i = 45; our $i = 45; for $i (0..67) { for $i (0..67) { last if $i == 10; last if $i == 10; investigate(); investigate(); } } print $i."\n"; print $i."\n"; sub investigate { sub investigate { print "\$i=$i\n"; print "\$i=$i\n"; } }
The difference is that the left program declares a my variable, while the right program declares an our variable.

However, when I run the programs, I get completely different behaviour inside the for loop:

45 0 45 1 45 2 45 3 45 4 45 5 45 6 45 7 45 8 45 9 $i=45 $i=45
Note that inside the for loop, the value of the top level my $i variable is not affected, while the global our $i variable gets temporarily affected. An interesting observation is made: Perl localizes the $i variable differently inside the for loop, depending on how $i is declared in the first place.

When the top level $i variable is declared as a my variable, the for loop is equivalent to -
my $i = 45; for (0..67) { my $i = $_; ... }
When the top level $i variable is declared as an our variable, the for loop is equivalent to -
our $i = 45; for (0..67) { local $i = $_; ...

In reply to Re: "for" surprise by Roger
in thread "for" surprise by fletcher_the_dog

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.