develooper Front page | perl.beginners | Postings from December 2002

Re: help with classes...

Thread Previous | Thread Next
Todd W
December 10, 2002 14:40
Re: help with classes...
Message ID:

"Christopher J Bottaro" <> wrote in message
> hey,
> i'm a c/c++ programmer struggling to pick up OO perl.  i've been reading
> perltoot and i have question about the following:
> package Person;
>     use strict;
>     sub new {
>         my $self  = {};
>         $self->{NAME}   = undef;
>         $self->{AGE}    = undef;
>         $self->{PEERS}  = [];
>         bless($self);           # but see below
>         return $self;
>     }
>     sub name {
>         my $self = shift;
>         if (@_) { $self->{NAME} = shift }
>         return $self->{NAME};
>     }
> ok, in the sub new(), i understand that $self is a ref and new() is
> it.  what does bless do (the single arg version).  i thought bless takes 2
> args:  what to bless and the name to bless it with...?  what else does
> do besides give something a type?

It marks the referent in the symbol table that $self refers to so that the
referent knows its associated with a class.

> in the sub name(), what is the first argument?  obviously its a reference
to a
> person object (or whatever new() returned).  but why?  i've written subs
> before and used shift(), but this is confusing me.  say i have $person =
> Person->new();  now i do $person->name();  i'm not passing it any
> so why is the sub name() receiving an argument which is a reference to a
> Person object?  does it have something to do with bless()?  something to
> with being a part of package?

$person->name(); does pass an argument to name(), a reference to a hash that
refers to the same hash $person does.

Think about this:

my($frank) = Person->new(); # class method -- $_[0] eq 'Person';

my($jimmy) = Person::new(); # plain 'ol function call -- $_[0] eq '';

my($mike) = $jimmy->new(); # object method -- $_[0] eq 'HASH(0x1abf0e0)';

Todd W.

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About