Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Perl Programming/Objects

From Wikibooks, open books for an open world
<Perl Programming
Previous: Code reuse (modules)IndexNext: Structure and style

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 calledbless, some magic variables (@ISA,AUTOLOAD,UNIVERSAL), the-> and some strong conventions for supporting inheritance and encapsulation.

An object is created using thepackage 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 callednew()

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 thenew 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 contextmy%bar;# All vars are declared as hashessubnew{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();

prints10

Further reading

[edit |edit source]


Previous: Code reuse (modules)IndexNext: Structure and style
Retrieved from "https://en.wikibooks.org/w/index.php?title=Perl_Programming/Objects&oldid=4234984"
Category:

[8]ページ先頭

©2009-2025 Movatter.jp