[英]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.