On Tue, Oct 15, 2002 at 09:26:33PM -0500, montana wrote:
> Take the following example from the perlboot manual:
> { package Horse;
> @ISA = qw(Animal);
> sub sound { "neigh" }
> sub name {
> my $self = shift;
> $$self;
> }
> sub named {
> my $class = shift;
> my $name = shift;
> bless \$name, $class;
> }
> }
> my $talking = Horse->named("Mr. Ed");
> print $talking->name, " says ", $talking->sound, "\n";
>
> When we create the instance, what values go into @_ so that
> $talking-name returns the de-referenced scalar "Mr. Ed", $class
> receives the value Horse, and $name receives the reference $talking?
> Or am I wrong on how this works?
You're close. You are correct that $class is set to "Horse". This is
because the constructor (named) was called as Horse->named(...).
However, $name is set to "Mr. Ed". When you call a method, the only
difference to calling a normal sub is that the first element of @_ will
be the name of the class, or the instance of the class upon which you
called the method. Then the rest of the parameters are added to @_.
So in this case, @_ = ("Horse", "Mr. Ed"). You can check this for
yourself by printing @_ as the first line in the method.
The constructor, then blesses $name into the class "Horse", or more
accurately, blesses a reference to $name. The bless function also
returns that blessed reference, and so this value is returned from the
constructor. This value is then assigned to $talking.
$talking is then an instance of the class Horse, which happens to be a
reference to a scalar holding the value "Mr. Ed".
The other methods work correctly because $talking knows to which class
it belongs, and it can also be dereferenced to find out the name of the
horse.
Later Randal introduces blessed hashes, which are a more usual container
for objects. In fact, it is rare to see blessed scalars outside of XS
code, so I am a little surprised at the order in which Randal introduces
these concepts, but as he has taught this a lot more than I have, I
suspect that he has found this order to be most helpful in general.
> Thanks.
> SA
>
> P.S. (Please use plain English, for I am not the most proficient Perl
> programmer yet.)
Hmmm. Perl OO in plain English. How'd I do?
--
Paul Johnson - [EMAIL PROTECTED]
http://www.pjcj.net
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]