Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

(dchetlin - static vs. closure) RE(3): lexical weirdness(?)

by dchetlin (Friar)
on Oct 26, 2000 at 07:42 UTC ( #38549=note: print w/replies, xml ) Need Help??

in reply to RE: RE: lexical weirdness(?)
in thread lexical weirdness(?)

There are at least two major differences between closures and static-via-my-if-0 variables.

Here's the first. Look closely at this code and see if you can figure out what its output will be before you run it.

#!/usr/bin/perl -w use strict; { my $closure; sub func_w_closure { print "Closure! ", $closure++, "\n"; func_w_closure($_[0]+1) if $_[0] < 3; } } sub func_w_static { my $static if 0; print "Static! ", $static++, "\n"; func_w_static($_[0]+1) if $_[0] < 3; } func_w_closure(0); func_w_static(0);

I'll use tilly's spoiler trick:

[~] $ dev/test/ Closure! 0 Closure! 1 Closure! 2 Closure! 3 Static! 0 Static! 0 Static! 0 Static! 0

In other words, the closure is the same variable through all calls, including recursive ones, while each recursive call to the func_w_static gets its own copy.

The cool thing about that, of course, is that if you call func_w_closure again, you see that each recursive instance keeps its value!

The other difference is that closures can be shared among functions -- if you stick another function into the lexical scope of `$static' above, some_function and your new function will refer to the same variable.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://38549]
[Corion]: Heh. After a bit of hacking, the Pg parser now "just" fails because some Win32 functions of Postgres aren't included in the lib I'm hacking up. Progress, I guess :)

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2018-03-23 21:13 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (296 votes). Check out past polls.