|Just another Perl shrine
simple anonymous subroutine and variable interpolation timing questionby tj_thompson (Monk)
|on Jun 23, 2011 at 19:59 UTC
tj_thompson has asked for the wisdom of the Perl Monks concerning the following question:
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:
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 :)