I
Irving Kimura
I'm a newcomer to Perl, and though I can already write useful
scripts, I'm still at the stage of learning about good Perl idioms.
Here I'm interested in learning more about static-like variables.
When programming C, I like using static variables to hold function-local
constants that will not change value throughout the program's
execution. E.g.
int foo( int bar, int baz ) {
static int frobozz = SOME_CONFIG_MACRO;
int retval;
/* do stuff with bar, baz, and frobozz */
return retval;
}
Here frobozz is initialized only once, no matter how often foo is
called.
In Perl, one can use block scoping to achieve a similar effect
(almost):
FOO_BLOCK:
{
my $frobozz = SOME_CONFIG_CONSTANT;
sub foo {
my ($bar, $baz) = @_;
# do stuff with $bar, $baz, and $frobozz;
$retval;
}
}
But there's a problem with this version of a static variable. If
a call to foo() happens lexically before FOO_BLOCK, then $frobozz
is undefined. This forces a potentially undesired ordering in the
placement of such sub definitions in the file.
The only way around this that I can think of is this:
FOO_BLOCK:
{
my $frobozz;
sub foo {
$frobozz ||= SOME_CONFIG_CONSTANT;
my ($bar, $baz) = @_;
# do stuff with $bar, $baz, and $frobozz;
$retval;
}
}
This means that $frobozz gets evaluated one extra time, tested,
and possibly assigned to (if SOME_CONFIG_CONSTANT happens to evaluate
to false) during every call to foo.
Is there a way to more closely replicate the behavior of C statics
than this?
TIA,
Irv
scripts, I'm still at the stage of learning about good Perl idioms.
Here I'm interested in learning more about static-like variables.
When programming C, I like using static variables to hold function-local
constants that will not change value throughout the program's
execution. E.g.
int foo( int bar, int baz ) {
static int frobozz = SOME_CONFIG_MACRO;
int retval;
/* do stuff with bar, baz, and frobozz */
return retval;
}
Here frobozz is initialized only once, no matter how often foo is
called.
In Perl, one can use block scoping to achieve a similar effect
(almost):
FOO_BLOCK:
{
my $frobozz = SOME_CONFIG_CONSTANT;
sub foo {
my ($bar, $baz) = @_;
# do stuff with $bar, $baz, and $frobozz;
$retval;
}
}
But there's a problem with this version of a static variable. If
a call to foo() happens lexically before FOO_BLOCK, then $frobozz
is undefined. This forces a potentially undesired ordering in the
placement of such sub definitions in the file.
The only way around this that I can think of is this:
FOO_BLOCK:
{
my $frobozz;
sub foo {
$frobozz ||= SOME_CONFIG_CONSTANT;
my ($bar, $baz) = @_;
# do stuff with $bar, $baz, and $frobozz;
$retval;
}
}
This means that $frobozz gets evaluated one extra time, tested,
and possibly assigned to (if SOME_CONFIG_CONSTANT happens to evaluate
to false) during every call to foo.
Is there a way to more closely replicate the behavior of C statics
than this?
TIA,
Irv