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} = "[email protected]";
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With