如何创建Perl模块?
问题描述:
如何为Perl编写模块?在Python中,您可以使用:
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")
答
一个类:
# lib/Class.pm
package Class;
use Moose;
# define the class
1;
导出功能的模块:
# lib/A/Module.pm
package A::Module;
use strict;
use warnings;
use Sub::Exporter -setup => {
exports => [ qw/foo bar/ ],
};
sub foo { ... }
sub bar { ... }
1;
使用这些脚本的脚本:
# 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();