Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create a Perl module?

Tags:

module

perl

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")
like image 753
WoW Avatar asked Feb 15 '09 12:02

WoW


4 Answers

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();
like image 113
jrockway Avatar answered Nov 19 '22 22:11

jrockway


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".

like image 26
tunnuz Avatar answered Nov 19 '22 20:11

tunnuz


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.

like image 14
draegtun Avatar answered Nov 19 '22 20:11

draegtun


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:

  • perlmod
  • perlmodlib
  • perlmodstyle
  • perlnewmod

  • perltoot: Tom's Object-Oriented Tutorial

  • perlboot: Barnyard Object-Oriented Tutorial

Good luck,

like image 11
brian d foy Avatar answered Nov 19 '22 20:11

brian d foy