in reply to Re^2: Trying to understand closures
in thread Trying to understand closures

my $x does actually change the value of $x .

Update: That's wrong. I don't know why I wrote that. As far as I know my creates a new variable so the later references to $x actually refer to a different instance of a variable even though they have the same name.

For example this code:
print __LINE__ . ": $x\n"; my $x = 123; print __LINE__ . ": $x\n"; my $x = 456; print __LINE__ . ": $x\n"; my $x; print __LINE__ . ": $x\n";
Prints out:
1: 3: 123 5: 456 7:

Replies are listed 'Best First'.
Re^4: Trying to understand closures
by ikegami (Patriarch) on Nov 24, 2006 at 05:54 UTC

    Each of those $x is a different variable.

    "my" variable $x masks earlier declaration in same scope at 585826.pl +line 4. "my" variable $x masks earlier declaration in same scope at 585826.pl +line 6. print __LINE__ . ": " . \$x . " = $x \n"; my $x = 123; print __LINE__ . ": " . \$x . " = $x \n"; my $x = 456; print __LINE__ . ": " . \$x . " = $x \n"; my $x; print __LINE__ . ": " . \$x . " = $x \n";
    1: SCALAR(0x0225fc4) = 3: SCALAR(0x022603c) = 123 5: SCALAR(0x1830b1c) = 456 7: SCALAR(0x1830ba0) =

    (Undefined warnings omitted.)

    Note that my $x does not always create a new variable. In my snippet, $x, $y and $z are the same variable every pass through the loop.