<html>
  <head>
    <meta content="text/html; charset=ISO-8859-1"
      http-equiv="Content-Type">
  </head>
  <body bgcolor="#FFFFFF" text="#000000">
    <div class="moz-cite-prefix">On 23/10/12 11:04, Mathew Robertson
      wrote:<br>
    </div>
    <blockquote
cite="mid:CABG5UsU-kn9VTjqx0+sYNHH-LhPZTDY0TOqkuEwvOUrT5LT-xQ@mail.gmail.com"
      type="cite">
      <div><br>
      </div>
      <div class="gmail_quote">To clarify, I would have expected $x to
        not be lexical... I am deliberately reusing $x in the child
        scope assignment, without localising $x (via 'my' or 'local'):
        <div><br>
        </div>
        <div>
          <div>my $x = 'foo';</div>
          <div>foreach $x (1..2) {</div>
          <div>  foreach $x ('a'..'c') {</div>
          <div>    print $x." ";</div>
          <div>  }</div>
          <div>  print $x." ";</div>
          <div>}</div>
          <div>print $x.$/;</div>
        </div>
        <div><br>
        </div>
        <div>gives: a b c 1 a b c 2 foo</div>
        <div>when I told the code to generate: a b c c a b c c c</div>
      </div>
    </blockquote>
    <br>
    $x is lexical. That's what declaring it with a my does... except...<br>
    you'll find that the following two loops are effectively identical.<br>
    <br>
    <pre>foreach $x ( 1..10) {</pre>
    <pre>    say $x;</pre>
    <pre>}</pre>
    <br>
    and <br>
    <br>
    <pre>{</pre>
    <pre>    local $x = 1;</pre>
    <pre>    while( $x < 10 ) {</pre>
    <pre>        say $x;</pre>
    <pre>    }</pre>
    <pre>}</pre>
    <br>
    Notice that extra set of parentheses and the local?<br>
    <br>
    As per <perldoc perlsyn> this is intentional:<br>
    <br>
          The "foreach" loop iterates over a normal list value and sets
    the<br>
           variable VAR to be each element of the list in turn.  If the
    variable<br>
           is preceded with the keyword "my", then it is lexically
    scoped, and is<br>
           therefore visible only within the loop.  <u><i><b>Otherwise,
          the variable is</b></i></u><u><i><b><br>
        </b></i></u><u><i><b>       implicitly local to the loop and
          regains its former value upon exiting</b></i></u><u><i><b><br>
        </b></i></u><u><i><b>       the loop.</b></i></u>  If the
    variable was previously declared with "my", it uses<br>
           that variable instead of the global one, but it's still
    localized to<br>
           the loop.  This implicit localization occurs only in a
    "foreach" loop.<br>
    <br>
    <br>
    No point arguing, it's existed this way for a long, long time.  ;)<br>
    <br>
        J<br>
  </body>
</html>