Packages, modules, classes and objects

17

Click here to load reader

description

This is the tenth set of slightly updated slides from a Perl programming course that I held some years ago. I want to share it with everyone looking for intransitive Perl-knowledge. A table of content for all presentations can be found at i-can.eu. The source code for the examples and the presentations in ODP format are on https://github.com/kberov/PerlProgrammingCourse

Transcript of Packages, modules, classes and objects

Page 1: Packages, modules, classes and objects

Perl Programming Perl Programming CourseCourse

Packages, modules, classes Packages, modules, classes and objectsand objects

Krassimir Berov

I-can.eu

Page 2: Packages, modules, classes and objects

ContentsContents

1.1. What is a module?What is a module?

2.2. What is a package?What is a package?

3.3. What is a class?What is a class?

4.4. What is an object?What is an object?

5.5. Working with objectsWorking with objects

• blessbless and and refref

• tietie and and tiedtied

• use and requireuse and require

6.6. Using ModulesUsing Modules

7.7. Creating a moduleCreating a module

Page 3: Packages, modules, classes and objects

What is a module?What is a module?

• A module is just a set of related functions and A module is just a set of related functions and variables in a library filevariables in a library file

• ...a Perl package with the same name as the file. ...a Perl package with the same name as the file.

• It is specifically designed to be reusable by other It is specifically designed to be reusable by other modules or programsmodules or programs

• May provide mechanism for exporting some of its May provide mechanism for exporting some of its symbols into the symbol table of any package symbols into the symbol table of any package using itusing it

• May function as a class definition and make its May function as a class definition and make its semantics available implicitly through method calls semantics available implicitly through method calls on the class and its objectson the class and its objects

• See Exporter and perlmodlibSee Exporter and perlmodlib

Page 4: Packages, modules, classes and objects

What is a package?What is a package?

• package NAMESPACEpackage NAMESPACE• declares the compilation unit as being in the given declares the compilation unit as being in the given namespacenamespace

• The scope of the package declaration is from the The scope of the package declaration is from the declaration itself through the end of the enclosing declaration itself through the end of the enclosing block, file, or eval (the same as the block, file, or eval (the same as the mymy operator) operator)

• Refer to things in other packages by prefixing the Refer to things in other packages by prefixing the identifier with the package name and a double colon: identifier with the package name and a double colon: $Package::Variable$Package::Variable

• See perlfunc/package, perlmod/PackagesSee perlfunc/package, perlmod/Packages

package Human;package Human;our $legs = 2;our $legs = 2;our $hands = 2;our $hands = 2;

Page 5: Packages, modules, classes and objects

What is a class?What is a class?

• There is no special class syntax in PerlThere is no special class syntax in Perl• A package acts as a class if it provides subroutines A package acts as a class if it provides subroutines

to act as methodsto act as methods• A class may be thought as a user-defined type.A class may be thought as a user-defined type.• use baseuse base to both load the base classes (packages) to both load the base classes (packages)

and inherit from themand inherit from them• A class should provide one or more ways to A class should provide one or more ways to

generate objectsgenerate objects

package Dog;package Dog;use base qw(Mammaluse base qw(Mammal););sub new {sub new { my $class = shift;my $class = shift; my $self = {};my $self = {}; bless $self, $class;bless $self, $class;}}

Page 6: Packages, modules, classes and objects

What is an object?What is an object?

• An Object is Simply a Reference An Object is Simply a Reference with user-defined typewith user-defined type

• Perl doesn't provide any special syntax for constructorsPerl doesn't provide any special syntax for constructors

• A Method is simply a SubroutineA Method is simply a Subroutine

• A method expects its first argument to be the object A method expects its first argument to be the object (reference) or package (string) it is being invoked on(reference) or package (string) it is being invoked on

• A constructor is a subroutine that returns a reference to A constructor is a subroutine that returns a reference to something "blessed" into a classsomething "blessed" into a class

• Constructors are often class methodsConstructors are often class methods

• You could think of the method call as just another form You could think of the method call as just another form of dereferencingof dereferencing

Page 7: Packages, modules, classes and objects

Working with objectsWorking with objects

• bless REF,CLASSNAMEbless REF,CLASSNAMEbless REFbless REF

• tells the thingy referenced by REF that it is tells the thingy referenced by REF that it is now an object in the CLASSNAME package now an object in the CLASSNAME package and returns the referenceand returns the reference

• If CLASSNAME is omitted, the current If CLASSNAME is omitted, the current package is usedpackage is used

• NOTE: Always use the two-argument version NOTE: Always use the two-argument version to enable inheritanceto enable inheritanceMake sure that CLASSNAME is a true valueMake sure that CLASSNAME is a true value

Page 8: Packages, modules, classes and objects

Working with objectsWorking with objects

• bless - Example:bless - Example:#bless.pl#bless.pl{{ package Dog;package Dog; sub new {sub new { my $class = shift;my $class = shift; my $self = {my $self = { name =>'Puffy',name =>'Puffy', nationality =>'bg_BG',nationality =>'bg_BG', };}; bless $self, $class;bless $self, $class; }} sub name {sub name { return $_[0]->{name}return $_[0]->{name} }}#...#...}}

Page 9: Packages, modules, classes and objects

Working with objectsWorking with objects

• ref EXPRref EXPRrefrefReturns a non-empty string if EXPR is a reference, the Returns a non-empty string if EXPR is a reference, the empty string otherwise. empty string otherwise. • If EXPR is not specified, $_ will be used. If EXPR is not specified, $_ will be used.

• The value returned depends on the type of thing the The value returned depends on the type of thing the reference is a reference to. reference is a reference to.

• Builtin types include:Builtin types include:SCALAR, ARRAY, HASH, CODE, REF, GLOB, LVALUE, SCALAR, ARRAY, HASH, CODE, REF, GLOB, LVALUE, FORMAT, IO, RegexpFORMAT, IO, Regexp

• If the referenced object has been If the referenced object has been blessblessed into a package, ed into a package, then that package name is returned instead.then that package name is returned instead.

• You can think of You can think of refref as a typeof operator. as a typeof operator.

• See ref.pl for MORE.See ref.pl for MORE.

Page 10: Packages, modules, classes and objects

Working with objectsWorking with objects

• tie VARIABLE,CLASSNAME,LISTtie VARIABLE,CLASSNAME,LIST• binds a variable to a package class that will provide the binds a variable to a package class that will provide the

implementation for the variableimplementation for the variable

• VARIABLE is the name of the variable to be VARIABLE is the name of the variable to be tiedtied

• CLASSNAME is the name of a class implementing objects CLASSNAME is the name of a class implementing objects of correct typeof correct type

• Any additional arguments are passed to the new method Any additional arguments are passed to the new method of the class (meaning TIESCALAR , TIEHANDLE , of the class (meaning TIESCALAR , TIEHANDLE , TIEARRAY , or TIEHASH )TIEARRAY , or TIEHASH )

• See perlfunc/tied, perltie, Tie::Hash, Tie::Array, See perlfunc/tied, perltie, Tie::Hash, Tie::Array, Tie::Scalar, and Tie::HandleTie::Scalar, and Tie::Handle

• See DB_File or the Config module for interesting tie See DB_File or the Config module for interesting tie implementations. See also tie.pl for EXAMPLEimplementations. See also tie.pl for EXAMPLE

Page 11: Packages, modules, classes and objects

Working with objectsWorking with objects

• tied VARIABLEtied VARIABLE

• Returns a reference to the object underlying Returns a reference to the object underlying VARIABLE VARIABLE

• The same value was originally returned by the tie The same value was originally returned by the tie call that bound the variable to a package. call that bound the variable to a package.

• Returns the undefined value if VARIABLE isn't Returns the undefined value if VARIABLE isn't tied to a package.tied to a package.

• See tie.pl and tied.pl for examplesSee tie.pl and tied.pl for examples

Page 12: Packages, modules, classes and objects

Working with objectsWorking with objects

• use Module VERSION LISTuse Module VERSION LISTuse Moduleuse Moduleuse VERSIONuse VERSION• It is exactly equivalent toIt is exactly equivalent to

• The BEGIN forces the The BEGIN forces the requirerequire and and importimport to to happen at compile time.happen at compile time.

• importimport imports the list of features into the current imports the list of features into the current packagepackage

• If no import method can be found, the call is skippedIf no import method can be found, the call is skipped• In use VERSION form VERSION has to be a numeric In use VERSION form VERSION has to be a numeric

argument such as 5.016, which will be compared to argument such as 5.016, which will be compared to $] $]

BEGIN { require Module; Module->import( LIST ); }BEGIN { require Module; Module->import( LIST ); }

Page 13: Packages, modules, classes and objects

Working with objectsWorking with objects

• require VERSIONrequire VERSIONrequire EXPRrequire EXPRrequirerequire

• demands that a library file be included if it hasn't demands that a library file be included if it hasn't already been includedalready been included

• The file is included via the do-FILE mechanism, The file is included via the do-FILE mechanism,

• Lexical variables in the invoking script will be Lexical variables in the invoking script will be invisible to the included code.invisible to the included code.

• The file must return true as the last statement to The file must return true as the last statement to indicate successful execution of any initialization indicate successful execution of any initialization codecode

• If EXPR is a bareword, the require assumes a ".pm" If EXPR is a bareword, the require assumes a ".pm" extension and replaces "::" with "/" in the filename extension and replaces "::" with "/" in the filename

Page 14: Packages, modules, classes and objects

Using ModulesUsing Modules

• See If you have what you need in CORE See If you have what you need in CORE modules or get the module you need modules or get the module you need using ppmusing ppmberov@berov:~> ppmberov@berov:~> ppm

Page 15: Packages, modules, classes and objects

Using ModulesUsing Modules

• ExampleExample

#using_modules.pl#using_modules.pluse strict; use warnings; use utf8;use strict; use warnings; use utf8;use FindBin;use FindBin;BEGIN {BEGIN { $ENV{APP_ROOT} = $FindBin::Bin .'/..';$ENV{APP_ROOT} = $FindBin::Bin .'/..';}}use lib($ENV{APP_ROOT}.'/lib');use lib($ENV{APP_ROOT}.'/lib');use Data::Table;#patched... See TODO in moduleuse Data::Table;#patched... See TODO in moduleuse Data::Dumper;use Data::Dumper;......

Page 16: Packages, modules, classes and objects

Packages, modules, classes Packages, modules, classes and objectsand objects

• RessourcesRessources

• Beginning Perl Beginning Perl (Chapter 11 – Object-Oriented Perl)(Chapter 11 – Object-Oriented Perl)

• perlboot - Beginner's Object-Oriented Tutorialperlboot - Beginner's Object-Oriented Tutorial

• perlobj - Perl objectsperlobj - Perl objects

• perltoot - Tom's object-oriented tutorial for perlperltoot - Tom's object-oriented tutorial for perl

• perltooc - Tom's OO Tutorial for Class Data in perltooc - Tom's OO Tutorial for Class Data in PerlPerl

• perlbot - Bag'o Object Tricks (the BOT)perlbot - Bag'o Object Tricks (the BOT)

Page 17: Packages, modules, classes and objects

Packages, modules, classes Packages, modules, classes and objectsand objects

Questions?Questions?