Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re^2: Interesting: a genuine Perl-bug

by liverpole (Monsignor)
on Sep 23, 2010 at 00:21 UTC ( #861412=note: print w/replies, xml ) Need Help??


in reply to Re: Interesting: a genuine Perl-bug
in thread Interesting: a genuine Perl-bug

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$..$/

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://861412]
help
Chatterbox?
[Corion]: But LPW was enjoyable, even though it's always a bit hectic due to cramming everything into one day
[Corion]: I have no feeling about how my talk was received, but I'm happy with it, which counts the most to me ;-D
[Corion]: Also, London is always a nice visit, as I got to meet a friend there, and spent some time offline, working on "minor" features of the shadertoy thing ;)
[marto]: maybe next year when the kids are a little older I'll have time to attend perl events in Europe
[Corion]: marto: Yeah - there isn't a Perl Day-Care at Perl events - we thought about it for YAPC::Europe 2012 but it's a gigantic effort to organize that

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (8)
As of 2016-12-07 09:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    On a regular basis, I'm most likely to spy upon:













    Results (125 votes). Check out past polls.