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

Re: help with classes...

Thread Previous | Thread Next
From:
Todd W
Date:
December 10, 2002 14:54
Subject:
Re: help with classes...
Message ID:
20021210225443.29334.qmail@onion.perl.org

"Christopher J Bottaro" <cjb@cs.utexas.edu> wrote in message
news:200212101510.25033.cjb@cs.utexas.edu...
> 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
1st
> argument?  or does that only happen when an object invokes the method?
like
> 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
sense".

HTH,

Todd W.



Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About