Hello monks. I have a question I'm sure has a very easy answer, but I'm not quite sure how to look for it.

I have a variable with some value in it. I would like to create an anonymous subroutine that will return the value of the variable. However, I'd like to lock in the return value of the subroutine to be the value of the variable when I create the subroutine as opposed to the current value of the variable when the subroutine is called. For example:

DB<10> $str = 'hi'; DB<11> $sub = sub {$str} DB<12> x &$sub 0 'hi' DB<13> $str = 'hello'; DB<14> x &$sub 0 'hello'

I would like the second call to &$sub to return 'hi' also, instead of the new value of $str. How do I force the variable to be interpolated at the time of the subroutine creation? I tried double quoting the var but that didn't do the trick either. I tried searching a bit, but the terms to use for this aren't obvious and I'm not getting much for results.

I appreciate any input. I'm sure I'll be giving myself a good facepalming shortly after someone points out the obvious :)


In reply to simple anonymous subroutine and variable interpolation timing question by tj_thompson

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.