Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

How do you figure that out?

First, don't put named subs inside loops or other subs. It makes no sense. The latter will even warn ("will not stay shared") if it captures anything from the sub its in.

Then the answer is simple: All variables declared before it in a scope that hasn't been closed.

my $x; <- this one. { my $y; <- not this one. ... } { my $z; <- this one. sub f { ... } }

For anonymous subs, it's a different story. Feel free to use them in loops and other subs. They'll pick up the variables that are visible when the sub is executed.

And why does a my variable that is in scope inside the loop's block

for localizes its iterator variable. Localizing is temporary replacing a variable with a new one.

You captured $num before the loop started. This is different from the $num of the first pass, which is different from $num of the second pass, ..., which is different from $num of the fifth pass.

(Ok, I lied. I believe an optimisation will actually cause the variable of the first pass to be reused for the subsequent passes, but that's transparent here.)


In reply to Re^3: closure clarity, please by ikegami
in thread closure clarity, please by 7stud

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 wandering the Monastery: (3)
As of 2024-04-25 14:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found