Hi all

Suppose you have the following dummy example of a closure: (The real example I'm working on do a little more interesting thing.)

my $print = emphasizePrint(); $print->("Hello World"); ## Prints "Hello World!!" sub emphasizePrint { my $k = "!!\n"; return sub { my ($str) = @_; eval (q{print "$str$k"}); print STDERR "Error: $@" if ($@); } }

The problem is that this example doesn't work because the eval statement is compiled at run-time where it is called, that is outside of the emphasizePrint subroutine and there $k is out of scope, right?

The solution would be to include $k in the returned subroutine but outside the eval statement, avoiding $k to be "garbage-collected". The subroutine emphasizePrint would look like this:

sub emphasizePrint { my $k = "!!\n"; return sub { $k; ## <- INSERTED my ($str) = @_; eval (q{print "$str$k"}); print STDERR "Error: $@" if ($@); } }

But I'm not fully comfortable with this solution. Is this correct? Is there another (better) way of coping with this?

Thank you very much in advance

citromatik


In reply to Scope problem in closures with an eval statement by citromatik

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.