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

Re: help with classes...

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

"Christopher J Bottaro" <> wrote in message
> hmm, i have more questions now.  how does one make class methods vs object
> methods?
> using the example from the tutorial...
<snip />
>     sub name {
>         my $self = shift;
>         if (@_) { $self->{NAME} = shift }
>         return $self->{NAME};
>     }
> what if we did Person->name()?  would it implicitly pass anything as the
> argument?  or does that only happen when an object invokes the method?
> this $person->name().

Why dont you print($self); after the shift() and see what you get? =0)

It would pass the string 'Person' as the first argument.

If you said: Person::name(); @_ would be empty.

> i don't see how Person->name() could pass a ref of it self as the first
> argument cuz there >is< no object.  thus sub name() could be rewritten as:

Right. Thats a class method

> sub name() {
> my $self = shift;
> if (!ref($self)) { return undef; }
> if (@_) { $self->{NAME} = shift }
> return $self->{NAME};
> }

If your function expects an object you need to do something to make sure its
getting something it knows what to do with.

For the subroutine above, it makes sure its a reference, but is it the right
reference? What if someone said:

use CGI;
Person::name( CGI->new() );

Your function was given a reference, but not the one it was expecting.

Stop in to your local book store or library and pick up the Perl Cookbook.
It answered all these questions for me.

As in another post, as opposed to C++ there not much magic going on. I dont
know how other people think, but to me, perl's OO support "just makes


Todd W.

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