无需包或对象引用即可调用方法

时间:2014-10-01 13:57:36

标签: perl

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

1 个答案:

答案 0 :(得分:4)

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

@Everyone = 0;

你不能在零上调用方法:

0->forename

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

my @Everyone;