繁体   English   中英

包含Perl类文件

[英]Include Perl class file

我有一个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”的代码似乎不正确,但我不知道如何解决此问题。 请帮忙...

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

use person;

如果person.pm所在的目录不在@INC ,则可以使用lib pragma进行添加:

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源文件的问题的解决方案。 通常,您会:

use lib "c:/some_dir_path";
use class_name;

当模块的源代码正在开发中时,下面的解决方案会更好,因为它会将模块重新加载到Perl的缓存中。 它确保每次需要时都重新加载类源代码,这意味着将要包含的文件的源代码中的任何更改都会在每次将文件包含在编译时或运行时中生效:

push (@INC,"c:/some_path_to_source_dir"); #directory contains perl source files

delete @INC{"class1.pl"}; #to reload class1
require "class1.pl";

delete @INC{"class2.pl"}; #to reload class2
require "class2.pl";

delete @INC{"class3.pl"}; #to reload class3
require "class3.pl";

我不知道这是否是一种好方法,请纠正我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM