perl - 包含 Perl 类文件

标签 perl oop class include require

我有一个 Perl 类文件(包):person.pl

package person;

sub create {
  my $this = {  
    name => undef,
    email => undef
  }

  bless $this;
  return $this;
}  

1;

我需要在另一个文件中使用这个类:test.pl

(注意person.pl和test.pl在同一个目录下)

require "person.pl";

$john_doe = person::create();
$john_doe->{name} = "John Doe";
$john_doe->{email} = "johndoe@example.com";

但是没有成功。

我正在使用 XAMPP 来运行 PHP 和 Perl。

我觉得用“require”来获取好像不太对 “人”类的代码,但我不知道 如何解决这个问题。请帮助...

最佳答案

首先,您应该将文件命名为 person.pm(对于 Perl 模块)。然后你可以用 use 加载它功能:

use person;

如果person.pm所在目录不在@INC中,可以使用lib添加它的编译指示:

use lib 'c:/some_path_to_source_dir';
use person;

其次,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;
}

然后将构造函数作为类方法调用:

use strict;   # Use strict and warnings in your main program too!
use warnings;
use person;

my $john_doe = person->new();

注意:在 Perl 中使用 $self 而不是 $this 更常见,但这实际上并不重要。 Perl 的内置对象系统非常小,对您的使用方式几乎没有限制。

关于perl - 包含 Perl 类文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5535275/

相关文章:

java - 多态与继承

javascript - uglifyjs 一个 javascript 类 - 意外的 token 错误

perl - 从 Perl 中的命令获取返回码和输出

perl - 在 Unix 中排序日期/时间

perl - 为什么 `perl Foo.pm` 和 `perl -I. -mFoo -e1` 的行为不同?

c++ - 如何在C++ Visual Studio中获得此输出?

java - 如何编写正确的 OOP 代码以避免出现字段初始化问题?

Javascript:如何获取每个 ClassName 的项目

c++ - 将二维数组显示为 map

perl - 从 Perl 或 shell 中的颠覆转储文件中获取最高修订号