如何编写简单的Perl模块
答案:1 悬赏:60
解决时间 2021-01-15 08:47
- 提问者网友:骑士
- 2021-01-14 10:37
如何编写简单的Perl模块
最佳答案
- 二级知识专家网友:我住北渡口
- 2021-01-14 11:55
# 存档为 /perl根目录/site/lib/My/Module1.pm;
package My::Module1;
sub new {
bless{
Var1 => "Value for Var1"
}, shift # 创建物件及其属性, 然後回传到主程序
}
sub getVar1 {
my $class = shift;
return $class->{Var1}
}
1; #这句很重要!!然後这个模块就可以用了, 以上是 perl OO 的典型例子, 另一种则是非 OO 的形式
# 存档为 /perl根目录/site/lib/My/Module2.pm;
package My::Module2;
require Exporter;
our @ISA = qw/Exporter/;
our @EXPORT = qw/printItems/; #外边要靠这个才能直接呼叫此模块里的涵数
sub printItems {
my @items = @_;
print "@items"
}
1; # 这句真的很重要!!现在来到你自己的主程序, main.pl
#!perl
use My::Module1;
use My::Module2;
$object = My::Module->new();
print $object -> getVar1; #"Value for Var1"
# getVar1() 是来自 My::Module1 的物件的方法
printItems( 'A'..'E' ) ; # "A B C D E"
# printItems() 是 Export 自 My::Module2 的涵数
package My::Module1;
sub new {
bless{
Var1 => "Value for Var1"
}, shift # 创建物件及其属性, 然後回传到主程序
}
sub getVar1 {
my $class = shift;
return $class->{Var1}
}
1; #这句很重要!!然後这个模块就可以用了, 以上是 perl OO 的典型例子, 另一种则是非 OO 的形式
# 存档为 /perl根目录/site/lib/My/Module2.pm;
package My::Module2;
require Exporter;
our @ISA = qw/Exporter/;
our @EXPORT = qw/printItems/; #外边要靠这个才能直接呼叫此模块里的涵数
sub printItems {
my @items = @_;
print "@items"
}
1; # 这句真的很重要!!现在来到你自己的主程序, main.pl
#!perl
use My::Module1;
use My::Module2;
$object = My::Module->new();
print $object -> getVar1; #"Value for Var1"
# getVar1() 是来自 My::Module1 的物件的方法
printItems( 'A'..'E' ) ; # "A B C D E"
# printItems() 是 Export 自 My::Module2 的涵数
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息!
大家都在看
推荐信息