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.

In reply to Re^2: Closures & aliases by ambrus
in thread Closures & aliases by BrowserUk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.