#!/usr/bin/perl -- use strict; # use warnings; sub factoryOne { my ($var) = (@_); print "factory: '$var'\n"; return sub { eval { print "eval: '$var'\n" }; } } sub factoryTwo { my ($var) = (@_); print "factory: '$var'\n"; return sub { my $estr = "print \"eval: '\$var'\n\""; eval $estr; } } sub factoryThree { my ($var) = (@_); print "factory: '$var'\n"; return sub { $var; my $estr = "print \"eval: '\$var'\n\""; eval $estr; } } my $f = factoryOne('lulz'); $f->(); my $g = factoryTwo('frunz'); $g->(); my $h = factoryThree('lulz'); $h->();
yields:
factory: 'lulz' eval: 'lulz' factory: 'frunz' eval: '' factory: 'lulz' eval: 'lulz'

the first factory works as expected, the second two don't, really.

two questions:
1) why isn't $var in scope inside the eval inside the closure inside factoryTwo?
2) why does referencing $var in the closure remedy 1) in factoryThree?


In reply to i don't understand this scope behavior w/ closures and eval by xandercrews

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.