Thanks for explaining.
I thought that when perl localizes a variable
(either with local or for)
it just saves the old value of the variable somewhere
(as an unnamed variable
in the lexical evironment of the block
in which you localize),
and restores it on exit.
(But it does the saving and restoring with an unwind-protect
so that if an exception brings out perl from the block,
the value gets restored.)
I belive that implementation
would not cause the faulty(?) behaiviour discussed
here.
I am still far from understanding perl internals,
so that may be a bad solution (and slower).
As you cannot localize a my variable in perl (which
might have some relation to how local is implemented),
I cannot reproduce that "bug" with local
instead of for.
Mit-scheme has the non-standard function
(Update:) special form
fluid-let, which is the equivalent of
perl's local (let is that of my).
With this, you can write
(let* ((v 2) (f (lambda () v))) (fluid-let ((v 5)) (f)))
This evaluates to 5, thus showing that f gets the new localized
value of v. If you change fluid-let to let, you get 2 of
course.
Update: This is of course just localization, not
a for loop, which may be quite different.
Because of the reason mentioned above,
you can not translate this code to perl as is.
If you use a global variable:
$v= 2; sub f {print $v} for $v (5) {f;}
or
$v= 2; sub f {print $v} {local $v= 5; f;}
you get 5 as expected. It is possible
that foreach is of a different nature than local in perl.
|