Reputation: 16869
Why would an uninitialized variable behave/interact differently than an initialized variable in this situation:
use strict;
use warnings;
our($foo) = 0;
BEGIN {
$foo = 2;
}
our($bar);
BEGIN {
$bar = 3;
}
print "FOO: <$foo>\n";
print "BAR: <$bar>\n";
results in:
$ perl test.pl
FOO: <0>
BAR: <3>
Perl version:
$ perl -v
This is perl 5, version 22, subversion 0 (v5.22.0) built for x86_64-linux
Upvotes: 2
Views: 203
Reputation: 386361
First of all, it's not an initializer; it's a plain old assignment. It happens when the code is executed, not when the variable is created.
Secondly, BEGIN
blocks are evaluated as soon as the block is compiled.
As such, what you wrote is basically equivalent to the following:
# Compile phase
use strict;
use warnings;
our $foo;
$foo = 2;
our $bar;
$bar = 3;
# Runtime phase
($foo) = 0;
($bar);
print "FOO: <$foo>\n";
print "BAR: <$bar>\n";
More precisely,
use strict;
.require strict;
.import strict;
.use warnings;
.require warnings;
.import warnings;
.our($foo) = 0;
. (Only creates $foo
.)BEGIN
block:
$foo = 2;
.BEGIN
block:
$foo = 2;
.our($bar);
. (Only creates $bar
.)BEGIN
block:
$bar = 3;
.BEGIN
block:
$bar = 3;
.print "FOO: <$foo>\n";
.print "BAR: <$bar>\n";
.($foo) = 0;
.($bar);
.print "FOO: <$foo>\n";
print "BAR: <$bar>\n";
As you can see,
2
to $foo
in 1.9.1, then you assign 0
to $foo
in 2.1.3
to $bar
in 1.12.1.Upvotes: 10