Bart Lateur wrote:
> On Mon, 03 Sep 2001 19:29:09 -0400, Ken Fox wrote:
> > The concept isn't the same. "local" variables are globals.
>
> This is nonsense.
> ...
> How are globals conceptually different than, say, globally scoped
> lexicals? Your description of global variables might just as well apply
> to file scoped lexicals.
Try this example:
use vars qw($x);
$x = 1;
sub foo { ++$x }
sub bar {
local($x);
$x = 2;
foo();
print "$x\n";
}
bar();
print "$x\n";
That prints:
3
1
If you use lexicals, you get the behavior that was *probably*
intended. "local" merely saves a copy of the variable's current
value and arranges for the variable to be restored when the
block exits. This is *fundamentally* different than lexical
variables.
It is possible to simulate the behavior of lexicals with
globals if you generate unique symbols for each instance of
each lexical. For example:
foreach (1..10) { my $x; push @y, \$x }
could compile to something like:
foreach (1..10) {
local($_temp) = gensym;
$::{$_temp} = undef;
push @y, \$::{$_temp}
}
The local used for $_temp must be guaranteed to never be
changed by any other sub. Ideally $_temp would be visible
only in the scope of the original lexical, but then $_temp
would be a lexical... ;)
- Ken