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

Re: help with classes...

Thread Previous | Thread Next
From:
christopher j bottaro
Date:
December 10, 2002 13:10
Subject:
Re: help with classes...
Message ID:
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...

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};
    }

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().

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:

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

which returns undef if it is invoked as a class method, essentially making 
name() an object method only.

am i making sense or am i just waaaaaay off?

thanks,
christopher

P.S.  any tips on the section in the perltoot "Class Data"?  i'm not making 
much sense of it.  so class data are just vars declared with "my" in scope of 
the class (package)?  in the example in perltoot, $Census is like that.  but 
the constructor for Person adds a ref of $Census into the hash.  why?  it has 
something to do with destruction but i'm not getting it.........

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