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

Re: help with classes...

Thread Previous
Paul Johnson
December 10, 2002 03:44
Re: help with classes...
Message ID:

christopher j bottaro said:
> hey,
> i'm a c/c++ programmer struggling to pick up OO perl.  i've been reading
> the  perltoot and i have question about the following:

Hopefully it won't be too much of a struggle.  In contrast to C++, there
is little magic going on behind the scenes.

Read the start of perlobj.  Bah, read the whole thing - it's not that bad ;-)

> 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
> returning  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...?

Yes, but if you only pass one arg, the second defaults to the name of the
package.  This is OK for a simple example, but is not good for

> what else does bless  do besides give something a type?

I think that's about it.

> in the sub name(), what is the first argument?  obviously its a
> reference to a  person object (or whatever new() returned).  but why?

Because name() is a method, and when called as such the object on which it
is called is passed in as the first argument.  C++ magically puts it in
"this", but as I recall cfront used to use the same trick of passing it as
the first argument to the method.  Perl owns up to this, and lets you do
what you will with it.  Most people say "my $self = shift;"

> 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 arguments  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 do  with being a part of package?

Paul Johnson -

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