thanos1983 has asked for the wisdom of the Perl Monks concerning the following question:
Dear Monks,
I am new to the OO programming in general and also in Perl. I found this tutorials Object Oriented Programming in PERL that I am following and trying to understand how to use Inheritance.
I have a created a similar code example from the tutorial, but I can not figure out how to call a method from another module without having to define the object inside the module.
Sample of code to replicate my problem:
mainl.pl
#!/usr/bin/perl use Employee; use strict; use warnings; my $object = new Person( "Thanos", "Test", 123456); # Get first name which is set using constructor. my $firstName = $object->getFirstName(); print "Before Setting First Name is : $firstName\n"; # Now Set first name using helper function. $object->setFirstName( "Than." ); # Now get first name set by helper function. $firstName = $object->getFirstName(); print "Before Setting First Name is : $firstName\n";
Person.pm
#!/usr/bin/perl use strict; use warnings; package Person; 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;
Employee.pm
#!/usr/bin/perl use strict; use warnings; package Employee; use Person; our @ISA = qw(Person); # inherits from Person my $firstName = $object->getFirstName(); print "This is the first name: " . $firstName . "\n"; 1; =comment How can I use the method my $firstName = $object->getFirstName(); without creating the object? =cut
The error that I am getting when I execute the code:
Global symbol "$object" requires explicit package name at Employee.pm +line 10. Compilation failed in require at main.pl line 2. BEGIN failed--compilation aborted at main.pl line 2.
How can I call the method, without the need to define the object again! I assume there is a way since I am using inheritance.
Thanks in advance for time and effort trying to answer my simple question.
|
|---|