in reply to Are we seeing syntax inconsistency?

Yes. $_ is a package variable. $index is a lexical. In the first case, you have a closure which closes over $index; in the second, you simply have an anonymous function that prints a global variable.

I do find it curious that you get 11 different $index variables, though; I would expect you’d get only one. I’m not entirely sure of how foreach works in this respect.

Makeshifts last the longest.

  • Comment on Re: Are we seeing syntax inconsistency?

Replies are listed 'Best First'.
Re^2: Are we seeing syntax inconsistency?
by Ovid (Cardinal) on Nov 11, 2005 at 05:11 UTC

    foreach has to create a fresh variable every time. Otherwise, when you keep a reference to one (as with the anonymous subroutine), they would all hold the same value every time a new value was assigned in the loop.

    (And thanks to Animator for clearing up my sloppy wording on this)

    Cheers,
    Ovid

    New address of my CGI Course.

      Actually that's not entirely correct.

      foreach does not create a variable. It is my that creates the variable. And my will use some free memory. My guess is that the references counter is increased by using the variable in an anonymous, subroutine (/closure). Which means that at the end of the foreach-block the reference counter is not 0 (and therfor the memory is not freed). Then that same part of the memory is not free at the start of the next iteration, so my will use some other memory.

      Some code:
      for my $x (0 .. 3) { print \$x }; ==> this code should print the same references for all 4 iterations.
      for my $x (0 .. 3) { print \$x; push @z, sub { $x; }; } ==>This code will print 4 different references.

        Which means Ovid’s assertion is correct. A new variable gets allocated through each iteration – only that most of the time, the space for the iterator variable from the last iteration happens to get recycled.

        Makeshifts last the longest.