in reply to Re: How do closures and variable scope (my,our,local) interact in perl?
in thread How do closures and variable scope (my,our,local) interact in perl?
That's not entirely true:
my $name; $name = 'red'; *$name = sub { "<FONT COLOR='$name'>@_</FONT>" }; $name = 'blue'; *$name = sub { "<FONT COLOR='$name'>@_</FONT>" }; $name = '<none>'; print red(), "\n"; print blue(), "\n"; __END__ <FONT COLOR='<none>'></FONT> <FONT COLOR='<none>'></FONT>
... but when the same is done in a loop, with a lexical variable declared beforehand, the result changes:
my $name; for $name ('red', 'blue') { *$name = sub { "<FONT COLOR='$name'>@_</FONT>" }; }; $name = '<none>'; print red(), "\n"; print blue(), "\n"; __END__ <FONT COLOR='red'></FONT> <FONT COLOR='blue'></FONT>
The behaviour changes again, if you use a global:
# global $name; for $name ('red', 'blue') { *$name = sub { "<FONT COLOR='$name'>@_</FONT>" }; }; $name = '<none>'; print red(), "\n"; print blue(), "\n"; __END__ <FONT COLOR='<none>'></FONT> <FONT COLOR='<none>'></FONT>
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: How do closures and variable scope (my,our,local) interact in perl?
by LanX (Saint) on Jun 16, 2009 at 16:00 UTC | |
by Corion (Patriarch) on Jun 16, 2009 at 16:14 UTC | |
by LanX (Saint) on Jun 16, 2009 at 16:51 UTC |