How do you write a module for Perl? In Python you can use:
# module.py
def helloworld(name):
print "Hello, %s" % name
# main.py
import module
module.helloworld("Jim")
A class:
# lib/Class.pm
package Class;
use Moose;
# define the class
1;
A module that exports functions:
# lib/A/Module.pm
package A::Module;
use strict;
use warnings;
use Sub::Exporter -setup => {
exports => [ qw/foo bar/ ],
};
sub foo { ... }
sub bar { ... }
1;
A script that uses these:
# bin/script.pl
#!/usr/bin/env perl
use strict;
use warnings;
use FindBin qw($Bin);
use lib "$Bin/../lib";
use Class;
use A::Module qw(foo bar);
print Class->new;
print foo(), bar();
Basically you create a file named Yourmodulename.pm
, whose contents are:
package Yourmodulename;
# Here are your definitions
1; # Important, every module should return a true value
Then the program that uses the module will look like:
#!/usr/bin/perl
use strict; # These are good pragmas
use warnings;
# Used modules
use Carp; # A module that you'll probably find useful
use Yourmodulename; # Your module
You may want to organize your modules in a hierarchical (and hopefully logical) way. To do so you create a tree of directories like:
Your/Module.pm
Your/Other/Module.pm
And then in your program:
use Your::Module;
use Your::Other::Module;
There are more facilities to export functions and variables from your module, you can take a look at Henning Koch's "Writing serious Perl: The absolute minimum you need to know".
An "exact" equivalent of your Python example in Perl would look like this:
# MyModule.pm
package MyModule;
sub helloworld {
my ( $name ) = @_;
print "Hello, $name\n";
}
1;
# main.pl
use MyModule;
MyModule::helloworld( 'Jim' );
For more, see the entry for package
in perlfunc documentation. For much more, see the perlmod documentation.
The last third of Intermediate Perl is devoted to module creation.
Whenever you want to know how to do something in Perl, check perltoc, the table of contents for the Perl documentation:
% perldoc perltoc
Several parts of the core Perl documentation can help you:
perlnewmod
perltoot: Tom's Object-Oriented Tutorial
Good luck,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With