Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
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 examining the Monastery: (10)
As of 2014-12-22 13:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (118 votes), past polls