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 ( [id://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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://911170]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2024-04-23 16:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found