我是perl的新手。我有一个计划要做。
1.我想创建一个简单的课程,其中包含学生姓名,掷骰号和6个学科标记的信息
我还想创建一个子程序来计算商标的百分比
3.还想通过创建子类来演示用户继承,子类将包含roll no,来自父类的名称以及添加新的字段地址和电话号码。
4.创建一个覆盖百分比子例程的方法。
我经历了很多perl文档,但却无法解决这个问题,我也无法解决2,3和4问题。
我现在的代码粘贴在下面,但似乎也没有用。任何人都可以让我知道我该怎么做这个程序,以便我可以学习所有这些?
我的代码:
class.pm
package class;
#constructor
sub new
{
#my ($class) = @_;
my ($class, %arg) = @_;
my $self =
{
_name => $arg{_name} ,
_roll_no => $arg{_roll_no} ,
_sub1 => $arg{_sub1} ,
_sub2 => $arg{_sub2} ,
_sub3 => $arg{_sub3} ,
_sub4 => $arg{_sub4} ,
_sub5 => $arg{_sub5} ,
_sub6 => $arg{_sub6}
};
, $class;
}
sub name { $_[0] -> {_name} }
sub roll_no { $_[0] -> {_roll_no} }
sub sub1 { $_[0] -> {_sub1}}
sub sub2 { $_[0] -> {_sub2}}
sub sub3 { $_[0] -> {_sub3}}
sub sub4 { $_[0] -> {_sub4}}
sub sub5 { $_[0] -> {_sub5}}
sub sub6 { $_[0] -> {_sub6}}
1;
我也创建了class1.pm
class1.pm
use class;
print "Object 1:\n\n";
my $obj1 = class->new(
name => "sam" ,
roll_no => "1" ,
sub1 => "99" ,
sub2 => "98" ,
sub3 => "97" ,
sub4 => "96" ,
sub5 => "95" ,
sub6 => "96"
);
print $obj1->name, "\n";
print $obj1->roll_no, "\n";
print $obj1->sub1, "\n";
print $obj1->sub2, "\n";
print $obj1->sub3, "\n";
print $obj1->sub4, "\n";
print $obj1->sub5, "\n";
print $obj1->sub6, "\n";
答案 0 :(得分:5)
这是为使您的测试代码有效而修复的类:
package class;
sub new {
my ($class, %arg) = @_;
my $self = {
_name => $arg{name},
_roll_no => $arg{roll_no},
_sub1 => $arg{sub1},
_sub2 => $arg{sub2},
_sub3 => $arg{sub3},
_sub4 => $arg{sub4},
_sub5 => $arg{sub5},
_sub6 => $arg{sub6}
};
return bless $self, $class;
}
sub name { $_[0]->{_name} }
sub roll_no { $_[0]->{_roll_no} }
sub sub1 { $_[0]->{_sub1} }
sub sub2 { $_[0]->{_sub2} }
sub sub3 { $_[0]->{_sub3} }
sub sub4 { $_[0]->{_sub4} }
sub sub5 { $_[0]->{_sub5} }
sub sub6 { $_[0]->{_sub6} }
有两件事需要修复:
%args
的name => "sam"
,而不是_name => "sam"
更多笔记:
有大量的模块可以帮助您将类Class::Accessor等类定义到更复杂的OO构建器,如Moose。对于后者,您的类定义将如下所示:
package class;
use Moose;
has name => (is => 'ro');
has roll_no => (is => 'ro');
has sub1 => (is => 'ro');
has sub2 => (is => 'ro');
has sub3 => (is => 'ro');
has sub4 => (is => 'ro');
has sub5 => (is => 'ro');
has sub6 => (is => 'ro');
has
为您声明一个属性,您可以免费获得构造函数。
答案 1 :(得分:1)