Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Making variables visible between calls.

by friedo (Prior)
on Dec 12, 2008 at 18:12 UTC ( #730004=note: print w/ replies, xml ) Need Help??


in reply to Making variables visible between calls.

Your anonymous subroutine can't see $var since it's compiled in a lexical scope separate from where it's executed. But it can have values passed into it as arguments.

sub create_f { my $func = shift; return sub { my $var = "xpto"; $func->( $var ); } } my $function = create_f( sub { print ">> $_[0] <<\n" } ); $function->();

Update: And if you want to specify the value at runtime, it's as easy as passing it into create_f.

sub create_f { my $func = shift; my $var = shift; return sub { $func->( $var ); } } my $function = create_f( sub { print ">> $_[0] <<\n" }, 'xpto' ); $function->();


Comment on Re: Making variables visible between calls.
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (10)
As of 2015-07-29 12:11 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 (263 votes), past polls