gpt4 book ai didi

perl - 没有包或对象引用无法调用方法

转载 作者:行者123 更新时间:2023-12-04 02:22:57 25 4
gpt4 key购买 nike

我正在努力学习 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。这两个文件都在同一目录中。

最佳答案

Everyone 数组中的第一个元素为零:

@Everyone = 0;

您不能在零上调用方法:

0->forename

要初始化一个空数组,只需使用

my @Everyone;

关于perl - 没有包或对象引用无法调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26143162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com