需要了解关于课程的一些事情

时间:2013-12-12 07:36:28

标签: perl

假设我正在上课

package Person;
# Class for storing data about a person
#person7.pm
use warnings;
use strict;
use Carp;
my @Everyone;
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;

我这样打电话

#!/usr/bin/perl
# classatr2.plx
use warnings;
use strict;
use Person;
print "In the beginning: ", Person->headcount, "\n";
my $object = Person->new (
   surname=> "Galilei",
   forename=> "Galileo",
   address=> "9.81 Pisa Apts.",
   occupation => "Philosopher"
);
print "Population now: ", Person->headcount, "\n";
my $object2 = Person->new (
   surname=> "Einstein",
   forename=> "Albert",
address=> "9E16, Relativity Drive",
occupation => "Theoretical Physicist"
);
print "Population now: ", Person->headcount, "\n";
print "\nPeople we know:\n";
for my $person(Person->everyone) {
   print $person->forename, " ", $person->surname, "\n";
}

输出

>perl classatr2.plx
In the beginning: 0
Population now: 1
Population now: 2
People we know:
Galileo Galilei
Albert Einstein
>

怀疑 - >我对这段代码感到怀疑

for my $person(Person->everyone) {
   print $person->forename, " ", $person->surname, "\n";
}

查询 - >这里$ person是哈希引用。为什么我们这样称呼$person->forename。而散列引用应该被称为$person->{$forename}

2 个答案:

答案 0 :(得分:8)

$person不仅仅是哈希引用;你之前有这句话bless($self, $class);。根据{{​​3}} perldoc;

bless REF,CLASSNAME
This function tells the thingy referenced by REF that it is now an object 
in the CLASSNAME package.

答案 1 :(得分:3)

关于OP对Elliott Frisch的回答所表达的疑问,$person->{surname}$person->surname之间的差异是:

$person->{surname}直接访问对象的内部数据。这违反了封装,许多人认为这是一种糟糕的做法。

$person->surnamesub surname对象上运行$person并返回结果。在这种特殊情况下,sub唯一能做的就是返回$person->{surname}的值,但它可以做其他事情。例如,如果您的Person类包含了Person的父母,那么$person->surname将能够首先检查Person是否定义了姓氏,如果没有,则返回$person->father->surname(或者,某些社团$person->father->forename . 'sson')而不是undef