Actually you should compare using a bare block (no BEGIN) which is the standard (older) way to have "state" variables.
I like 'state' but the old way is still useful if you need a pair of cooperating subs (or more):
% steph@ape (/home/stephan) %
% cat state_old.px
#!/usr/bin/perl+
{
my $var = 10;
sub next1 { ++$var; }
sub next1_odd {
if ($var % 2 == 0) {
++$var;
}
else {
++$var;
++$var;
}
}
}
$\ = qq{\n};
print next1() for 1..5;
print next1_odd();
% steph@ape(/home/stephan) %
% perl+ -w state_old.px
11
12
13
14
15
17
cheers
--stephan
-
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.
|