Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re^3: Trying to understand closures

by superfrink (Curate)
on Nov 24, 2006 at 05:51 UTC ( [id://585825]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://585825]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (9)
As of 2024-03-28 08:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found