use strict; use warnings; my $foobar_o = Foo::Bar->new( "object o" ); printf "%s\n", $foobar_o->text(1); # -- # Package # -- package Foo::Bar; # Package namespace 'our' globals (which must be forward-declared.) # These go in BEGIN so they work from an in-file package too! our $data; BEGIN { our $data = { 1 => "one", 2 => "two", 100 => "one hundred", }; } # Fairly minimal constructor, passed an optional "name" argument: sub new { my $class = shift; my $name = shift // ""; $class = ref($class) || $class; # subclass boilerplate. my $self = { name=>$name }; bless $self, $class; return $self; } # 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;