When I type in the following code and run it, it types <FONT COLOR=’foo’></FONT>. However, when I add my to the loop variable (for my $name (@colors)), it types the expected <FONT COLOR=’red’></FONT>. Can anyone explain why?
@colors = qw(red blue green yellow orange purple violet);
$name = 'foo';
for $name (@colors) {
no strict 'refs';
*$name = sub { "<FONT COLOR='$name'></FONT>" };
}
print red();
In your loop you create several subs. These subs can see all the variables of the context that they are created in.
If we use local / global variables, the sub will always see the latest value (The interpolation of the variable into the string does’nt happen at compile-time or “definition-time”, but when the sub is executed.) In our case, the current value outside the loop is
foo.If we use lexical variables with
my, the variable that we used inside the loop is invisible outside of the loop and invisible in all other iterations of the loop. However, it is still visible to the sub itself. This is called a closure. Closures only work with lexical variables and are a powerful method to achieve information hiding or to construct specifically tailored subs like in the example code.