Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: local & global function

by Jenda (Abbot)
on Oct 17, 2018 at 11:12 UTC ( [id://1224149]=note: print w/replies, xml ) Need Help??


in reply to local & global function

Maybe what you are after is somewhat like this:

use strict; { # just a block my $test; # the lexical one sub foo { print "In foo: \$test=$test\n"; $test = "Hello world"; print "In foo: \$test=$test\n"; } sub bar { print "In bar \$test=$test\n"; } } my $test; # the global one print "Global \$test=$test\n"; foo(); print "Global \$test=$test\n"; bar(); print "Global \$test=$test\n";

The two functions are defined in a block and therefore share the lexical (please do not use the term local in Perl) variables declared within that block ABOVE the functions.

Jenda
Enoch was right!
Enjoy the last years of Rome.

Replies are listed 'Best First'.
Re^2: local & global function (closures)
by LanX (Saint) on Oct 17, 2018 at 12:30 UTC
    > The two functions are defined in a block and therefore share the lexical

    Additional note: this is a fine example for using Closures.

    The two functions are "closing" over the lexical variable $test.

    And this $test has a lexical (i.e. static) scope restricted to the block.

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

    PS: it also demonstrates that closure don't need to be anonymous. There is a widespread misconception in some other languages that "closure" is a synonym for "anonymous function".

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (2)
As of 2025-12-12 18:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your view on AI coding assistants?





    Results (92 votes). Check out past polls.

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.