I have a Perl class file (package): person.pl
package person;
sub create {
my $this = {
name =>开发者_开发问答 undef,
email => undef
}
bless $this;
return $this;
}
1;
and i need to use this class in another file: test.pl
(note that person.pl and test.pl are in the same directory)
require "person.pl";
$john_doe = person::create();
$john_doe->{name} = "John Doe";
$john_doe->{email} = "johndoe@example.com";
but it didn't come to success.
I'm using XAMPP to run both PHP & Perl.
I think it doesn't seem right to use "require" to get the code of the class 'person', but i don't know how to resolve this problem. Please help...
First of all, you should name the file person.pm (for Perl Module). Then you can load it with the use function:
use person;
If the directory where person.pm is located is not in @INC
, you can use the lib pragma to add it:
use lib 'c:/some_path_to_source_dir';
use person;
Secondly, Perl doesn't have special syntax for constructors. You named your constructor create
(which is ok, but non-standard), but then tried to call person::new
, which doesn't exist.
If you're going to be doing object-oriented programming in Perl, you should really look at Moose. Among other things, it creates the constructor for you.
If you don't want to use Moose, here are some other improvements you can make:
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;
}
Then call the constructor as a class method:
use strict; # Use strict and warnings in your main program too!
use warnings;
use person;
my $john_doe = person->new();
Note: It's more common in Perl to use $self
rather than $this
, but it doesn't actually matter. Perl's built-in object system is very minimal and places few restrictions on how you use it.
I found a solution for my problem of loading Perl source files from another Perl file in the same directory. Normally you would:
use lib "c:/some_dir_path";
use class_name;
The solution below is better when the module's source code is under development, as it reloads the module in Perl's cache. It ensures the reloading of class source code each time it requires, meaning any change in the source code of the to-be-included file will effect each time the file is included in compilation or in runtime:
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";
I don't know whether it's a good way, please correct me.
精彩评论