Reputation: 2023
Suppose i am having class
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;
And i am calling like this
#!/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";
}
Ouput
>perl classatr2.plx
In the beginning: 0
Population now: 1
Population now: 2
People we know:
Galileo Galilei
Albert Einstein
>
Doubt -> I am having doubt in this part of code
for my $person(Person->everyone) {
print $person->forename, " ", $person->surname, "\n";
}
Query -> here $person is a hash reference. Why we are calling like $person->forename
. Whereas hash ref should be called as $person->{$forename}
Upvotes: 1
Views: 89
Reputation: 46235
Regarding the OP's doubts expressed in comments to Elliott Frisch's answer, the difference between $person->{surname}
and $person->surname
is:
$person->{surname}
directly accesses the object's internal data. This violates encapsulation and many people consider it a poor practice as a result.
$person->surname
runs sub surname
on the $person
object and returns the result. In this particular case, the only thing that sub
does is return the value of $person->{surname}
, but it could do other things. For instance, if your Person
class included the Person's parents, then $person->surname
would be able to first check whether the Person had a surname defined and, if not, return $person->father->surname
(or, in some societies, $person->father->forename . 'sson'
) instead of undef
.
Upvotes: 3
Reputation: 201527
$person
is NOT JUST a hash reference; you had this line bless($self, $class);
earlier. Per the bless perldoc;
bless REF,CLASSNAME
This function tells the thingy referenced by REF that it is now an object
in the CLASSNAME package.
Upvotes: 8