Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

comment on

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

One technique for 'static' variables in Perl (that you should be able to adapt to your underlying problem) is to wrap the sub in a bare block (or possibly a BEGIN block depending on initialization requirements and such). Your pseudo-code example becomes:

#!/usr/bin/perl -w use strict; foo(4); foo(); { my $bar; sub foo { $bar = shift unless defined $bar; print "$bar\n"; } } __END__

Which, in the case of an expensive initialization can be along the lines of:

#!/usr/bin/perl -w use strict; print scalar localtime(),"\n"; slow_once(5); slow_once(); { my $expensive_thingy; sub slow_once { unless (defined $expensive_thingy) { # make expensive thingy: sleep 5; $expensive_thingy = shift; } print scalar localtime()," :$expensive_thingy:\n"; } } __END__ OUTPUT: Sat Nov 3 15:55:31 2001 Sat Nov 3 15:55:36 2001 :5: Sat Nov 3 15:55:36 2001 :5:

If you wanted to create more than one expensive thingy, go with a parameterized sub that sets up the expensive thingy and returns a closure that does what you want with it.


In reply to Re: help with scoping (code), part 2 by danger
in thread help with scoping (code), part 2 by deprecated

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

    No recent polls found