note
liverpole
Hi [sundialsvc4],
<p>It's a very cool feature of 5.10 which mimics the <c>static</c> 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.
</p><p>For example, to perform initialization only once the first time a subroutine is called, you could do this:
<c>
#!/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() ...
</c>
</p><p>Or to define a subroutine which returns a unique integer each time it's called:
<c>
#!/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
</c>
<div class="pmsig"><div class="pmsig-465654">
<hr />
<font size="1">
s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
</font>
</div></div>
861269
861342