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} // ""; } # 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} // "" ); return $s; } # Explicit RC to support require() and use(). # This is only useful when the package is a real module file. 1;