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:
If the directory where person.pm is located is not in
@INC, you can use the lib pragma to add it:Secondly, Perl doesn’t have special syntax for constructors. You named your constructor
create(which is ok, but non-standard), but then tried to callperson::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:
Then call the constructor as a class method:
Note: It’s more common in Perl to use
$selfrather 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.