2
我正在學習Perl的調用方法,我通過文檔在Perl.org離不開包或對象引用
我得從教程下面的代碼運行,它拋出的錯誤:
Can't call method "forename" without a package or object reference.
封裝代碼(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;
調用代碼(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";
}
我看不出爲什麼會引發錯誤。我在Windows上使用Perl 5,版本16。這兩個文件都在同一個目錄中。
person7.pm文件位於與調用代碼相同的目錄中。包名稱是Person。 – 2014-10-01 14:00:22
這是正確的。根據我所遵循的教程,軟件包名稱是Person,但文件名是Person7.pm,本教程使用語句爲Person7。如果我聲明「使用Person」而不是「使用Person7」,它不能找到pm文件。 – 2014-10-01 14:02:19
你是否檢查過「每個人」都會回來,你認爲它是什麼? – 2014-10-01 14:11:04