4

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?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
no1
  • 717
  • 2
  • 8
  • 21

3 Answers3

7

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.

ysth
  • 96,171
  • 6
  • 121
  • 214
  • 2
    @ApoorvaShankar, you might want to read [this answer](http://stackoverflow.com/a/659198/8355) to the question [How do I choose a package name for a custom Perl module that does not collide with builtin or CPAN packages names?](http://stackoverflow.com/q/658955/8355) – cjm Oct 01 '13 at 07:22
4

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

Myforwik
  • 3,438
  • 5
  • 35
  • 42
3

Test is a preexisting Perl module, and it is found in @INC before the Test.pm in your current directory. (You're loading the wrong Test.pm.)

Rename your module to MyTest or similar.

Kevin Richardson
  • 3,592
  • 22
  • 14