What is the mistake in this object oriented program?

I learn perl, and when I tried to do object orientation, I ran into 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 mistake in this object oriented program?

+4
source share
3 answers

Test is the name of the module that is part of the standard perl distribution. Your use Testdownloads this instead of your test; Choose a different name for your module.

+7
source

Your problem is that you already have a module called Test.pm elsewhere in your default directories.

Try running perl like:

perl -I./ test.pl

./( ) @INC ( , ).

+4

Testis a pre-existing module Perl, and it is in @INCto Test.pmin your current directory. (You are loading the wrong one Test.pm.)

Rename your module to MyTestor similar.

+3
source

All Articles