我想创建一个Perl类.
这是我的代码:
#!/usr/ bin/perl
package Data;
sub new
{ my ($class, $student) = @_;
$class = shift;
$student = shift;
$student = {_firstName => <>,
_lastName => <>,
_matric => <>,
};
bless $student,$class;
print $student;
}
&new;
Run Code Online (Sandbox Code Playgroud)
我收到了这个错误:
main = HASH(0x215fc40)在source_file.pl第12行使用未初始化的值$ class.在source_file.pl第12行显式祝福''(假设包main).
我使用dcoder,我认为它不支持分离程序.但是虽然我纠正了它,但它仍然没有输出.我试图打印,$self但它留下了一个错误.这是整个代码:
#!/usr/ bin/perl
use strict;
use warnings 'all';
package student;
sub new {
my $class = shift;
my ($first, $last, $matric) = @_;
my $self = {
_firstName => $first,
_lastName => $last,
_matric => $matric,
};
bless $self, $class;
}
my $self = student->new('victor','valdes','csc');
print $self;
Run Code Online (Sandbox Code Playgroud)
这是错误:
学生= HASH(0x238ae98)
对不起,我真的很陌生,但仍然不明白.
这看起来非常像一个家庭作业问题,所以我很想给你一个完整的答案.您似乎对Perl知之甚少,并且几乎没有花时间阅读Perl的面向对象的想法,使用疯狂的猜测填补空白.你不会那样学习那种语言
你永远不应该使用&符调用Perl子程序,并且需要在类或对象上调用方法,所以&new应该是Data->new(...).您编写的每个Perl源文件也应该以use strict和开头use warnings 'all'
这是创建对象的一种非常奇怪的方式.您通常会创建一个单独的Perl程序,它use Data然后my $object = Data->new($student).相反,您正在调用&new,它不传递任何参数,并且是您未初始化值错误的原因
你的$student价值应该是什么并不明显,但在使用它shift来获取它的价值@_后,用哈希引用覆盖它
您还应该通过new构造函数调用传递散列内容的值,而不是让模块本身读取STDIN.您也没有达到chomp这些值,因此他们将保留您不太想要的终止换行符
我建议您将代码分成Data.pm(可能是Student.pm?),main.pl然后使用常量值编写代码,而不是从键盘读取代码
像这样的东西
package Student;
use strict;
use warnings 'all';
sub new {
my $class = shift;
my ($first, $last, $matric) = @_;
my $self = {
_firstName => $first,
_lastName => $last,
_matric => $matric,
};
bless $self, $class;
}
1;
Run Code Online (Sandbox Code Playgroud)
#!/usr/bin/perl
use strict;
use warnings 'all';
use Student;
my $student = Student->new('John', 'Smith', 1987);
Run Code Online (Sandbox Code Playgroud)