Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: simple anonymous subroutine and variable interpolation timing question

by wind (Priest)
on Jun 23, 2011 at 21:20 UTC ( #911170=note: print w/ replies, xml ) Need Help??


in reply to simple anonymous subroutine and variable interpolation timing question

I see three possible solutions to this:

  1. 1) Save the value in another variable, using Readonly if you want to ensure the saved value doesn't get modified.
  2. 2) Use a closure.
  3. 3) Interpolate the variable in an eval'd anonymous subroutine.
use Readonly; my $str = 'hi'; # String Readonly my $STR => $str; # Closure my $closure = do { my $var = $str; sub { $var } }; # Evalled Sub my $anonsub = do { (my $var = $str) =~ s/(["\\])/\\$1/g; eval qq{sub {"$var"}}; }; $str = 'hello'; print "string = $STR\n"; print "closure = ", $closure->(), "\n"; print "anonsub = ", $anonsub->(), "\n";


Comment on Re: simple anonymous subroutine and variable interpolation timing question
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://911170]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (10)
As of 2015-07-07 10:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (88 votes), past polls