I'm working on learning Perl and I'm running through the documentation at Perl.org
I've got the below code from the tutorial and it's throwing the error:
Can't call method "forename" without a package or object reference.
Package code (person7.pm):
package Person;
#Class for storing data about a person
#person7.pm
use warnings;
use strict;
use Carp;
my @Everyone = 0;
sub new {
my $class = shift;
my $self = {@_};
bless( $self, $class );
push @Everyone, $self;
return $self;
}
#Object accessor methods
sub address { $_[0]->{address} = $_[1] if defined $_[1]; $_[0]->{address} }
sub surname { $_[0]->{surname} = $_[1] if defined $_[1]; $_[0]->{surname} }
sub forename { $_[0]->{forename} = $_[1] if defined $_[1]; $_[0]->{forename} }
sub phone_no { $_[0]->{phone_no} = $_[1] if defined $_[1]; $_[0]->{phone_no} }
sub occupation { $_[0]->{occupation} = $_[1] if defined $_[1]; $_[0]->{occupation} }
#Class accessor methods
sub headcount { scalar @Everyone }
sub everyone {@Everyone}
1;
Calling code (classatr2.plx):
#!/usr/bin/perl
# classatr2.plx
use warnings;
use strict;
use Person7;
print "In the beginning: ", Person->headcount, "\n";
my $object = Person->new(
surname => "Galilei",
forename => "Galileo",
address => "9.81 Pisa Apts.",
occupation => "bombadier"
);
print "Population now: ", Person->headcount, "\n";
my $object2 = Person->new(
surname => "Einstein",
forename => "Albert",
address => "9E16, Relativity Drive",
occupation => "Plumber"
);
print "Population now: ", Person->headcount, "\n";
print "\nPeople we know:\n";
for my $person ( Person->everyone ) {
print $person->forename, " ", $person->surname, "\n";
}
I cannot see why it is throwing an error. I'm using Perl 5, version 16 on Windows. Both files are in the same directory.
The first element in the Everyone array is zero:
@Everyone = 0;
You can't call a method on a zero:
0->forename
To initialize an empty array, use just
my @Everyone;
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