Forwarded Message From:"christopher j bottaro" <[EMAIL PROTECTED]>Reply-to:[EMAIL PROTECTED]:[EMAIL PROTECTED]:help with classes...Date:Tue, 10 Dec 2002 04:45:15 -0600MIME-Version:1.0Content-Type:text/plain; charset="us-ascii"Content-Transfer-Encoding:7bitMessage-Id:<[EMAIL PROTECTED]>
Plain Text Attachment [ Save to my Yahoo! Briefcase | Download File ] 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: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...? what else does bless do besides give something a type?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 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?thanks for the help....=)christopher Hi Chris, I felt the same way when I first started out with classes, but keep at it, it's not as hard as it looks :) The single argument form of bless blesses the reference into the current package. So if you have : package Person; my $ref=\%hash; bless($ref); $ref will be blessed into the Person package. Once you have blessed a reference into a package, whenever you call a method(sub) via that reference, the first argument perl passes to that method is the reference. This happens behind the scenes so when you call $ref->subname() and $ref is in the Person package, perl substitutes that statement for Person::subname($ref); so $ref->destroy('Ring'); when $ref is in the Lotr package ends up as Lotr::destroy($ref,'Ring'); So in order to get to the other args, you do a shift to remove the ref from the @_ array. Hope that's been of help. Cheers. Image by FlamingText.com --------------------------------- Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now