Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

comment on

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

It's a very cool feature of 5.10 which mimics the static variable of C.  State variables don't lose their data, even when they go out of scope, so you can use them for cases where you want data to persist, without having to use globals.

For example, to perform initialization only once the first time a subroutine is called, you could do this:

#!/usr/bin/perl -w use feature qw{ state }; use strict; use warnings; for (1..5) { some_sub(); } sub some_sub { (state $b_initialized++) or initialize(); print "Now doing the main work of some_sub() ...\n"; } sub initialize { print "Initializing....\n"; # ... etc ... } __END__ === Output === Initializing.... Now doing the main work of some_sub() ... Now doing the main work of some_sub() ... Now doing the main work of some_sub() ... Now doing the main work of some_sub() ... Now doing the main work of some_sub() ...

Or to define a subroutine which returns a unique integer each time it's called:

#!/usr/bin/perl -w use feature qw{ state }; use strict; use warnings; for (1..5) { printf "Got the value %d\n", unique_integer(); } sub unique_integer { return ++(state $ncalls); } __END__ === Output === Got the value 1 Got the value 2 Got the value 3 Got the value 4 Got the value 5

s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/

In reply to Re^2: Interesting: a genuine Perl-bug by liverpole
in thread Interesting: a genuine Perl-bug by sundialsvc4

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: (5)
As of 2024-04-16 13:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found