[LA.pm] Alias to a dynamically scoped variable?
Brian Cooke
mrkoffee at saltedsnail.com
Sat Aug 27 17:15:46 PDT 2005
> Just wondering, is it possible to create an alias to a dynamically
> scoped variable?
>
> E.g, such as in this case $foo & $bar both equal 20?
>
> {
> my ($foo, $bar);
> *foo = *bar;
>
> $foo = 10;
> $bar = 20;
>
> print "foo: $foo\n";
> print "bar: $bar\n";
> }
>
> When run with warnings, it's clear that the aliasing is taking place
> on the global versions of foo, not my my guys.
William,
The "my" variables are lexically scoped, rather than dynamically scoped
(i.e., package variables localized at runtime using "local"). You are
correct: The *foo = *bar is manipulating the symbol table, and lexicals
don't live there. An interesting module that will alias lexical variables
is Lexical::Alias. If you say:
use Lexical::Alias;
{
my ($foo, $bar);
alias $foo, $bar;
$foo = 10;
$bar = 20;
print "\$foo: $foo\n";
print "\$bar: $bar\n";
}
the output will be:
$foo: 20
$bar: 20
Cheers,
Brian
More information about the Losangeles-pm
mailing list