I am learning perl and when I tried to do object orientation, I encountered errors, This is the code, Test.pm
#!/usr/bin/perl
package Test;
sub new
{
my $class = shift;
my $self = {
_firstName => shift,
_lastName => shift,
_ssn => shift,
};
# Print all the values just for clarification.
print "First Name is $self->{_firstName}\n";
print "Last Name is $self->{_lastName}\n";
print "SSN is $self->{_ssn}\n";
bless $self, $class;
return $self;
}
sub setFirstName {
my ( $self, $firstName ) = @_;
$self->{_firstName} = $firstName if defined($firstName);
return $self->{_firstName};
}
sub getFirstName {
my( $self ) = @_;
return $self->{_firstName};
}
1;
and test.pl
#!/usr/bin/perl
use Test;
$object = Test::new( "Mohammad", "Saleem", 23234345); # Get first name which is set using constructor.
$firstName = $object->getFirstName();
print "Before Setting First Name is : $firstName\n";
# Now Set first name using helper function.
$object->setFirstName( "Mohd." );
# Now get first name set by helper function.
$firstName = $object->getFirstName();
print "Before Setting First Name is : $firstName\n";
and when I try to run, It shows some erroe like this,
Can't locate object method "new" via package "Test" at test.pl line 2.
What is the error in this object oriented program?
Your problem is that you already have a module named Test.pm at some other location in your default included directories.
Try running perl as:
perl -I./ test.pl
That will prepend the directory ./ (ie. the current directory) to the beginning of @INC (which is a special variable containing a list of directories to load modules from).
Test is the name of a module that is part of the standard distribution of perl. Your use Test
is loading that instead of your Test; pick another name for your module.
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