There's no interpolation involved. The sub contains a lookup of a variable's content, so the variable needs to remain unchange if you want the output of the lookup to be constant.
You can do this by copying the value of $str into into a variable that doesn't change, and using that variable instead.
sub make_closure {
my ($str) = @_;
return sub { $str };
}
my $str = 'hi';
my $sub = make_closure($str);
say $sub->(); # 'hi'
$str = 'hello';
say $sub->(); # 'hi'
You could actually interpolate the current value into code, but producing code is trickier.
my $str = 'hi';
my $sub = eval qq{ sub { "\Q$str\E" } } or die $@;
say $sub->(); # 'hi'
$str = 'hello';
say $sub->(); # 'hi'
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|