Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the error in this object oriented program?

Tags:

oop

perl

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?

like image 947
no1 Avatar asked Dec 09 '22 12:12

no1


2 Answers

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).

like image 41
Myforwik Avatar answered Dec 11 '22 10:12

Myforwik


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.

like image 171
ysth Avatar answered Dec 11 '22 12:12

ysth