Jump to content
Wikibooks The Free Textbook Project

Perl Programming/Objects

From Wikibooks, open books for an open world

Objects

[edit | edit source ]

When Perl was initially developed, there was no support at all for object-orientated (OO) programming. Since Perl 5, OO has been added using the concept of Perl packages (namespaces), an operator called bless, some magic variables (@ISA, AUTOLOAD, UNIVERSAL), the -> and some strong conventions for supporting inheritance and encapsulation.

An object is created using the package keyword. All subroutines declared in that package become object or class methods.

A class instance is created by calling a constructor method that must be provided by the class, by convention this method is called new()

Let's see this constructor.

packageObject;
subnew{
returnbless{},shift;
}
subsetA{
my$self=shift;
my$a=shift;
$self->{a}=$a;
}
subgetA{
my$self=shift;
return$self->{a};
}

Client code can use this class something like this.

my$o=Object->new;
$o->setA(10);
print$o->getA;

This code prints 10.

Let's look at the new contructor in a little more detail:

The first thing is that when a subroutine is called using the -> notation a new argument is pre-pended to the argument list. It is a string with either the name of the package or a reference to the object (Object->new() or $o->setA. Until that makes sense you will find OO in Perl very confusing.

To use private variables in objects and have variables names check, you can use a little different approach to create objects.

packagemy_class;
usestrict;
usewarnings;
{
# All code is enclosed in block context
my%bar;# All vars are declared as hashes
subnew{
my$class=shift;
my$this=\do{my$scalar};# object is a reference to scalar (inside out object)
bless$this,$class;
return$this;
}
subset_bar{
my$this=shift;
$bar{$this}=shift;
}
subget_bar{
my$this=shift;
return$bar{$this};
}
}

Now you have good encapsulation - you cannot access object variables directly via $o->{bar}, but only using set/get methods. It's also impossible to make mistakes in object variable names, because they are not a hash-keys but normal perl variables, needed to be declared.

We use them the same way like hash-blessed objects:

my$o=my_class->new();
$o->set_bar(10);
print$o->get_bar();

prints 10

Further reading

[edit | edit source ]


AltStyle によって変換されたページ (->オリジナル) /