http://qs1969.pair.com?node_id=1146731


in reply to Behavior of 'our' variables in the package-namespace

When writing OO classes, try to stay away from initialising globals in the outer class definition. Doing that requires (as you have seen) funky work arounds, BEGIN blocks and the like. Its better to encapsulate your packages more clearly, such as the following:

use strict; use warnings; my $foobar_o = Foo::Bar->new( name => "object o" ); printf "%s\n", $foobar_o->text(1); # -- # Package # -- package Foo::Bar; # Package namespace 'our' globals (which must be forward-declared.) our $data; # Fairly minimal constructor, passed an optional "name" argument: sub new { my $class = shift; $class = ref($class) || $class; # subclass boilerplate. my %params = @_; initialise(); my $self = bless {}, $class; foreach my $key (keys %params) { my $func = lc $key; next unless $self->can("$func"); $self->$func($params{$key}); } return $self; } sub initialise { return if defined $data; $data = { 1 => "one", 2 => "two", 100 => "one hundred", }; } sub name { my $self = shift; my $value = shift; $self->{name} = $value if defined $value; return $self->{name} // "<unnamed object>"; } # Silly example method that returns the "text" keyed by %$data. sub text { my $self = shift; my $query = shift or return ''; # Sanity check, making sure the package namespace $data exists: die "Uh-oh, data is not defined!" unless defined $data; my $s = sprintf( "%s: %s is %s", $self->name(), $query, $data->{$query} // "<query value not defined>" ); return $s; } # Explicit RC to support require() and use(). # This is only useful when the package is a real module file. 1;
Notice how the inclusion of an initialise() function gets rid of the BEGIN block, useful in avoiding paying the piper if you don't actually create any objects of this class for whatever reason. Also notice that the use of an accessor shifts all of the code for that accessor to one clearly defined location, so if you decide to change anything about that piece of data it won't affect anything else (this becomes a lot more important when you start having very complex objects with complex rules defining how items are updated and default values).

I also like using named parameters for the constructor, even when only passing one or two parameters. It makes inheritance and future expansion of the class a lot simpler. Combining that with using accessors to get and set values makes the constructor incredibly simple.