nic*_*ola 1 oop perl class require include
我有一个Perl类文件(包):person.pl
package person;
sub create {
my $this = {
name => undef,
email => undef
}
bless $this;
return $this;
}
1;
Run Code Online (Sandbox Code Playgroud)
我需要在另一个文件中使用这个类:test.pl
(请注意,person.pl和test.pl位于同一目录中)
require "person.pl";
$john_doe = person::create();
$john_doe->{name} = "John Doe";
$john_doe->{email} = "johndoe@example.com";
Run Code Online (Sandbox Code Playgroud)
但它没有取得成功.
我正在使用XAMPP来运行PHP和Perl.
我认为使用"require"获取类'person'的代码似乎不对,但我不知道如何解决这个问题.请帮忙...
cjm*_*cjm 12
首先,您应该将文件命名为person.pm(对于Perl模块).然后你可以使用use函数加载它:
use person;
Run Code Online (Sandbox Code Playgroud)
如果person.pm所在的目录不在@INC,您可以使用lib pragma添加它:
use lib 'c:/some_path_to_source_dir';
use person;
Run Code Online (Sandbox Code Playgroud)
其次,Perl没有构造函数的特殊语法.你命名了你的构造函数create(这是好的,但非标准),但后来试图调用person::new,这是不存在的.
如果您要在Perl中进行面向对象编程,那么您应该真正关注Moose.除此之外,它还为您创建构造函数.
如果您不想使用Moose,可以进行以下一些其他改进:
package person;
use strict; # These 2 lines will help catch a **lot** of mistakes
use warnings; # you might make. Always use them.
sub new { # Use the common name
my $class = shift; # To allow subclassing
my $this = {
name => undef;
email => undef;
}
bless $this, $class; # To allow subclassing
return $this;
}
Run Code Online (Sandbox Code Playgroud)
然后将构造函数作为类方法调用:
use strict; # Use strict and warnings in your main program too!
use warnings;
use person;
my $john_doe = person->new();
Run Code Online (Sandbox Code Playgroud)
注意:在Perl中使用$self而不是使用它更常见$this,但实际上并不重要.Perl的内置对象系统非常小,对您的使用方式几乎没有限制.
| 归档时间: |
|
| 查看次数: |
2416 次 |
| 最近记录: |