First, let's get the incorrect terminology out of the way. Lexical and package variables are two different kinds of variables, and they are mutually exclusive. There's no such thing as lexical package variables.
>perl -le"package PkgA; my $foo = 'abc'; package PkgB; print $foo" abc
I usually use the term global variable for what you call lexical package variables. It's not perfect, but it's not outright wrong.
Now back to the subject. Why would you initialize a variable twice? That's bad, without or without BEGIN. If I saw code that looked like the following, I'd have a talk with you. And yet, that's exactly what you are doing.
my $stuff1; my $stuff2 = undef; my $stuff3 = undef; my $stuff4 = undef; $stuff1 = 'stuff1 stuff'; $stuff2 = 'stuff2 stuff'; $stuff3 = 'stuff3 stuff'; $stuff4 = 'stuff4 stuff'; print "stuff 1: $stuff1\n"; print "stuff 2: $stuff2\n"; print "stuff 3: $stuff3\n"; print "stuff 4: $stuff4\n";
You code without BEGINs should be
my $stuff1 = 'stuff1 stuff'; my $stuff2 = 'stuff2 stuff'; my $stuff3 = 'stuff3 stuff'; my $stuff4 = 'stuff4 stuff'; print "stuff 1: $stuff1\n"; print "stuff 2: $stuff2\n"; print "stuff 3: $stuff3\n"; print "stuff 4: $stuff4\n";
So your code should be
my $stuff1; my $stuff2; my $stuff3; BEGIN { $stuff1 = 'stuff1 stuff'; $stuff2 = 'stuff2 stuff'; $stuff3 = 'stuff3 stuff'; } my $stuff4; INIT { $stuff4 = 'stuff4 stuff'; } print "stuff 1: $stuff1\n"; print "stuff 2: $stuff2\n"; print "stuff 3: $stuff3\n"; print "stuff 4: $stuff4\n";
Of ir you had anything complex, an adherent to the quoted practice would do
my $stuff; BEGIN { $stuff = undef; ... ... ... ... Some complex code to initialize $stuff. ... ... ... }
instead of
my $stuff; BEGIN { ... ... ... ... Some complex code to initialize $stuff. ... ... ... }
In reply to Re^2: Use of uninitialized variables?
by ikegami
in thread Use of uninitialized variables?
by Zadeh
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |