On 18 Jun 2001 17:00:28 -0500, Nick Transier wrote:
> @Next will become a class (or package) variable, but it is not set yet 
> because I have another function which does that after the object is created. 
> It is meant to be an array of pointers or references I guess. Is there 
> anything I can do to quell the error messages without wrongly initializing 
> the var?
> 
> 
<snip />

There is an import difference between class variables abd attributes.
Attributes belong to an object, but class variables are the same for all
objects of that class. See code below for an example of both types of
variables.  As for how to get rid of the error messages: use references,
don't use variables that have not been decalared, and read up on
anonymous hashes and arrays.

<code>
#!/usr/bin/perl

use strict;

my $fred   = Cartoon->new;
my $barney = Cartoon->new;

$fred->name('Fred');   #these are attributes they belong
$barney->name('Barney'); #to the objects that hold them

$fred->spouse('Wilma'); #so are these
$barney->spouse('Betty');

Cartoon->town('Bedrock'); #this, however, belongs to both $fred and
$barney

$fred->print_info;
$barney->print_info;

package Cartoon;

{ #class variables and methods
        my $town;
        sub town { return ($town =  $_[1] || $town);
        }
}

sub new {
        my $class = shift;
        $class    = ref($class) || $class;
        my $self  =  {
                '_name'   => '',
                '_spouse' => ''
        };

        return bless $self, $class;
}

sub name {
        my ($self, $name) = @_;
        return ($self->{_name} = $name || $self->{_name});
}

sub spouse {
        my ($self, $spouse) = @_;
        return ($self->{_spouse} = $spouse || $self->{_spouse});
}

sub print_info {
        my $self = shift;
        print $self->name, " lives in ", ref($self)->town,
              " with ", $self->spouse, "\n";
}
</code>

<output>
Fred lives in Bedrock with Wilma
Barney lives in Bedrock with Betty
</output>


--
Today is Prickle-Prickle, the 23rd day of Confusion in the YOLD 3167
All Hail Discordia!


Reply via email to