> I'm try my best

And you had 99% of it right.

> package pt;
> use 5.0000;
> $a="ok";  #for public using
> $b="It's";
> 
> # I don't know why put the newsubroutine in this package,
> # perhaps, it is a constructer, I copy from PERL's manual,
> # but it seem don't do anything.

Most of what you wrote is redundant in this
particular case. You could have written:

    package foo;
    sub bar { bless \$qux };
    .
    .
    package waldo;
    $emerson = foo->new;

As you can see, $emerson is just a reference to $qux.
And $qux is undefined, but has one special property:
it's been blessed, which is how you turn a reference
into an object (which is just a reference that knows
what package it belongs to). Simple, really.

As you start to do more complex things, your constructor
needs to get a bit more clever.

In particular, what if the following call appears:

    oof->new;

and oof ISA (inherits from) foo, and has no constructor
defined, hence inheriting its constructor from foo?

Well, bless with one argument (as used in my snippet
above) associates that argument with the current
package, in the above case, foo, thus constructing a
foo object not an oof object. So one needs to find out
what package name was used to call the constructor
(the package name is conveniently passed as the
first argument whenever a sub is called using the
object oriented syntax) and then use the two argument
form of bless:

> sub new { 
>     my $type = shift;
>     my $self = {};
>     bless $self,$type;
> }

The $self = {} bit is so that the object can carry around
data as well as being blessed (which, applied to a mere
scalar, means you can only access subs (methods)).

> package main;       # My application
> use pt
> $c=pt->new();
> print $c->displaysub().$a;

The $a is assumed to be in the main package.

Use either:

    print $c->displaysub().$ct::a;
    
or use our:

    package pt;
    our $a;
    package main;
    print $c->displaysub().$ct::a;

or create displaya, an equivalent of displaysub,
only for $a, and call it as a class sub:

    package pt;
    our $a;
    package main;
    print $c->displaysub().ct->displaya;

hth

Reply via email to