package Mytest; use strict; use warnings; my $var = 1; 1; #### use strict; use warnings; use Mytest; print $Mytest::var . "\n"; #### use strict; use warnings; use Mytest; print $var; #### use Mytest; print $var; #### use Mytest; print $Mytest::var; #### #!/usr/bin/perl -w package Problem; use strict; use warnings; use Scalar::Util qw(refaddr); { my %key1_of; # leave blank test my %key2_of = (); # initialize test my %key3_of; BEGIN { %key3_of = (); # initialize with a BEGIN } sub new { my ($class, $ar1, $ar2, $ar3) = @_; my $new_object = bless \do{my $anon_scalar}, $class; $key1_of{refaddr($new_object)} = $ar1; $key2_of{refaddr($new_object)} = $ar2; $key3_of{refaddr($new_object)} = $ar3; return $new_object; } sub get_key1 { my $self = shift; return $key1_of{refaddr($self)}; } sub get_key2 { my $self = shift; return $key2_of{refaddr($self)}; } sub get_key3 { my $self = shift; return $key3_of{refaddr($self)}; } } 1; # Here's a user of the above object. package Main; use strict; use warnings; # Below: Creating values for the sake of showing the issue at hand... # First variable: assigning undef (declaring its initial value), # but due to a subroutine or other complex series of processing, it # gets assigned a value during a BEGIN block my $p1 = undef; # using the 'always assign a value' paradigm here my $p2; # leaving it blank for now my $p3 = undef; # same 'always assign' paradigm here, but not used in 'begin' # some processing happens in here; for example, let's say these variables are # dependent on user input or automatic config files, so $p1, $p2, $p3 might # not ever be used. It just turns out that this time, they all are. # However, the user of the package creates these instances of the object in a # begin block, and for whatever reason, the user can't avoid doing this. BEGIN { $p1 = Problem->new('P11', 'P12', 'P13'); $p2 = Problem->new('P21', 'P22', 'P23'); } $p3 = Problem->new('P31', 'P32', 'P33'); sub printit # for display purposes { my $p = shift; if (defined $p) { print " k1: " . $p->get_key1() . "\n"; my $k2 = $p->get_key2(); $k2 = "(undef)" if ! defined $k2; print " k2: $k2\n"; print " k3: " . $p->get_key3() . "\n"; } else { print " Error: Object is undefined.\n"; } }; print "P1:\n"; printit($p1); print " (Due to scoping of the undef assignment, the object itself is lost.)\n"; print "P2:\n"; printit($p2); print " (Note loss of key 2's value; it's lost because %key2_of\n" . " is assigned to () after the object's creation).\n"; print "P3:\n"; printit($p3); print " (As expected, no issues at all).\n";