Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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/scope.pl 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.

-dlc


In reply to (dchetlin - static vs. closure) RE(3): lexical weirdness(?) by dchetlin
in thread lexical weirdness(?) by jimt

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (3)
As of 2024-04-24 22:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found