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.
The most traditional way of setting up a module is as follows:
package Foo::Bar;
our @ISA = qw(Exporter); # Tells perl what to do with...
our @EXPORT = qw(sub1 sub2 sub3); # automatically exported subs
our @EXPORT_OK = qw(sub4 sub5); # exported only when demanded
# code for subs, constants, package variables here
1; # Doesn't actually have to be 1, just a 'true' value.
and as others have said, you can use it like so:
use Foo::Bar;
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();