A Sample Module
Earlier, we said that there are two flavors of modules: traditional or object-oriented. We’ll show you the shortest examples of each.
An object-oriented module is the easy one to show since it doesn’t need much infrastructure to communicate with its user. Everything happens through methods:
package Bestiary::OO 1.001;
sub new {
my( $class, @args ) = @_;
bless {}, $class;
}
sub camel { "one–hump dromedary" }
sub weight { 1024 }
### more methods here
1;A program that uses it does all its work through methods:
use v5.10;
use Bestiary::OO;
my $bestiary = Bestiary::OO–>new; # class method
say "Animal is ", $bestiary–>camel(),
" has weight ", $bestiary–>weight();To construct a traditional module called Bestiary, create a file called Bestiary.pm that looks like this:
package Bestiary 1.001;
use parent qw(Exporter);
our @EXPORT = qw(camel); # Symbols to be exported by default
our @EXPORT_OK = qw($weight); # Symbols to be exported on request
### Include your variables and functions here
sub camel { "one–hump dromedary" }
$weight = 1024;
1; # end with an expression that evaluates to trueA program can now say use
Bestiary to be able to access the camel function (but not the $weight variable), and use Bestiary qw(camel $weight) to access both
the function and the variable:
use v5.10; use Bestiary qw(camel $weight); say "Animal is ", camel(), " has weight $weight";
You can also create modules that dynamically load code written in C, although we don’t cover that here.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access