SlideShare una empresa de Scribd logo
1 de 17
Descargar para leer sin conexión
Perl Programming
                 Course
            Packages, modules, classes
                   and objects



Krassimir Berov

I-can.eu
Contents
1. What is a module?
2. What is a package?
3. What is a class?
4. What is an object?
5. Working with objects
  • bless and ref
  • tie and tied
  • use and require
6. Using Modules
7. Creating a module
What is a module?
• A module is just a set of related functions and
  variables in a library file
   • ...a Perl package with the same name as the file.
• It is specifically designed to be reusable by other
  modules or programs
• May provide mechanism for exporting some of its
  symbols into the symbol table of any package
  using it
• May function as a class definition and make its
  semantics available implicitly through method calls
  on the class and its objects
• See Exporter and perlmodlib
What is a package?
• package NAMESPACE
  • declares the compilation unit as being in the given
    namespace
  • The scope of the package declaration is from the
    declaration itself through the end of the enclosing
    block, file, or eval (the same as the my operator)
  • Refer to things in other packages by prefixing the
    identifier with the package name and a double colon:
    $Package::Variable
  • See perlfunc/package, perlmod/Packages
 package Human;
 our $legs = 2;
 our $hands = 2;
What is a class?
• There is no special class syntax in Perl
• A package acts as a class if it provides subroutines
  to act as methods
• A class may be thought as a user-defined type.
• use base to both load the base classes (packages)
  and inherit from them
• A class should provide one or more ways to
  generate objects
  package Dog;
  use base qw(Mammal);
  sub new {
      my $class = shift;
      my $self = {};
      bless $self, $class;
  }
What is an object?
• An Object is Simply a Reference
  with user-defined type
• Perl doesn't provide any special syntax for constructors
• A Method is simply a Subroutine
• A method expects its first argument to be the object
  (reference) or package (string) it is being invoked on
• A constructor is a subroutine that returns a reference to
  something "blessed" into a class
• Constructors are often class methods
• You could think of the method call as just another form
  of dereferencing
Working with objects
• bless REF,CLASSNAME
  bless REF
 • tells the thingy referenced by REF that it is
   now an object in the CLASSNAME package
   and returns the reference
 • If CLASSNAME is omitted, the current
   package is used
 • NOTE: Always use the two-argument version
   to enable inheritance
   Make sure that CLASSNAME is a true value
Working with objects
• bless - Example:
 #bless.pl
 {
     package Dog;
     sub new {
         my $class = shift;
         my $self = {
             name =>'Puffy',
             nationality =>'bg_BG',
         };
         bless $self, $class;
     }

      sub name {
          return $_[0]->{name}
      }
 #...
 }
Working with objects
• ref EXPR
  ref
 Returns a non-empty string if EXPR is a reference, the
 empty string otherwise.
  • If EXPR is not specified, $_ will be used.
  • The value returned depends on the type of thing the
    reference is a reference to.
  • Builtin types include:
    SCALAR, ARRAY, HASH, CODE, REF, GLOB, LVALUE,
    FORMAT, IO, Regexp
  • If the referenced object has been blessed into a package,
    then that package name is returned instead.
  • You can think of ref as a typeof operator.
  • See ref.pl for MORE.
Working with objects
• tie VARIABLE,CLASSNAME,LIST
 • binds a variable to a package class that will provide the
   implementation for the variable
 • VARIABLE is the name of the variable to be tied
 • CLASSNAME is the name of a class implementing objects
   of correct type
 • Any additional arguments are passed to the new method
   of the class (meaning TIESCALAR , TIEHANDLE ,
   TIEARRAY , or TIEHASH )
 • See perlfunc/tied, perltie, Tie::Hash, Tie::Array,
   Tie::Scalar, and Tie::Handle
 • See DB_File or the Config module for interesting tie
   implementations. See also tie.pl for EXAMPLE
Working with objects
• tied VARIABLE
  • Returns a reference to the object underlying
    VARIABLE
  • The same value was originally returned by the tie
    call that bound the variable to a package.
  • Returns the undefined value if VARIABLE isn't
    tied to a package.
  • See tie.pl and tied.pl for examples
Working with objects
• use Module VERSION LIST
  use Module
  use VERSION
  • It is exactly equivalent to
 BEGIN { require Module; Module->import( LIST ); }

  • The BEGIN forces the require and import to
    happen at compile time.
  • import imports the list of features into the current
    package
  • If no import method can be found, the call is skipped
  • In use VERSION form VERSION has to be a numeric
    argument such as 5.016, which will be compared to
    $]
Working with objects
• require VERSION
  require EXPR
  require
  • demands that a library file be included if it hasn't
    already been included
  • The file is included via the do-FILE mechanism,
  • Lexical variables in the invoking script will be
    invisible to the included code.
  • The file must return true as the last statement to
    indicate successful execution of any initialization
    code
  • If EXPR is a bareword, the require assumes a ".pm"
    extension and replaces "::" with "/" in the filename
Using Modules
• See If you have what you need in CORE
  modules or get the module you need
  using ppm
 berov@berov:~> ppm
Using Modules
• Example


 #using_modules.pl
 use strict; use warnings; use utf8;
 use FindBin;
 BEGIN {
     $ENV{APP_ROOT} = $FindBin::Bin .'/..';
 }
 use lib($ENV{APP_ROOT}.'/lib');
 use Data::Table;#patched... See TODO in module
 use Data::Dumper;
 ...
Packages, modules, classes
             and objects
• Ressources
  • Beginning Perl
    (Chapter 11 – Object-Oriented Perl)
  • perlboot - Beginner's Object-Oriented Tutorial
  • perlobj - Perl objects
  • perltoot - Tom's object-oriented tutorial for perl
  • perltooc - Tom's OO Tutorial for Class Data in
    Perl
  • perlbot - Bag'o Object Tricks (the BOT)
Packages, modules, classes
and objects




Questions?

Más contenido relacionado

Destacado

Tiempos futuros
Tiempos futuros Tiempos futuros
Tiempos futuros Ana Martin
 
UTE_ESTRATEGIA EN EMPRENDIMIENTOS SOCIALES Y CULTURA ORGANIZACIONAL
UTE_ESTRATEGIA EN EMPRENDIMIENTOS SOCIALES Y CULTURA ORGANIZACIONALUTE_ESTRATEGIA EN EMPRENDIMIENTOS SOCIALES Y CULTURA ORGANIZACIONAL
UTE_ESTRATEGIA EN EMPRENDIMIENTOS SOCIALES Y CULTURA ORGANIZACIONALMonica Ordoñez
 
La publicidad en la era digital - Evoca
La publicidad en la era digital - EvocaLa publicidad en la era digital - Evoca
La publicidad en la era digital - EvocaCarlos Terrones Lizana
 
Miguel Valls - MED-SV Cleantech Fund - Stanford Jan410
Miguel Valls - MED-SV Cleantech Fund - Stanford Jan410Miguel Valls - MED-SV Cleantech Fund - Stanford Jan410
Miguel Valls - MED-SV Cleantech Fund - Stanford Jan410Burton Lee
 
2010 Pep Talk Presentation
2010 Pep Talk Presentation2010 Pep Talk Presentation
2010 Pep Talk PresentationDavid Bienvenue
 
Formatos educativos Cs Ns JBA
Formatos educativos   Cs Ns JBAFormatos educativos   Cs Ns JBA
Formatos educativos Cs Ns JBANaturales Alberdi
 
Telco sector deck (Private Life of Mail)
Telco sector deck (Private Life of Mail)Telco sector deck (Private Life of Mail)
Telco sector deck (Private Life of Mail)Royal Mail MarketReach
 
Marketing Informatico (diapositiva)
Marketing Informatico (diapositiva)Marketing Informatico (diapositiva)
Marketing Informatico (diapositiva)eydaroxy
 
Master mind de negocios e inglés
Master mind de negocios e inglésMaster mind de negocios e inglés
Master mind de negocios e inglésJulio Nieto
 
Porque estudiar Arquitectura???
Porque estudiar Arquitectura???Porque estudiar Arquitectura???
Porque estudiar Arquitectura???Kenia_04
 
Ecuaciones diofánticas 02
Ecuaciones diofánticas 02Ecuaciones diofánticas 02
Ecuaciones diofánticas 02FdeT Formación
 
G Feismic Dafety Of Rchools Repal
G Feismic Dafety Of Rchools RepalG Feismic Dafety Of Rchools Repal
G Feismic Dafety Of Rchools RepalDIPECHO Nepal
 

Destacado (16)

Registration 2011[1]
Registration 2011[1]Registration 2011[1]
Registration 2011[1]
 
Tiempos futuros
Tiempos futuros Tiempos futuros
Tiempos futuros
 
UTE_ESTRATEGIA EN EMPRENDIMIENTOS SOCIALES Y CULTURA ORGANIZACIONAL
UTE_ESTRATEGIA EN EMPRENDIMIENTOS SOCIALES Y CULTURA ORGANIZACIONALUTE_ESTRATEGIA EN EMPRENDIMIENTOS SOCIALES Y CULTURA ORGANIZACIONAL
UTE_ESTRATEGIA EN EMPRENDIMIENTOS SOCIALES Y CULTURA ORGANIZACIONAL
 
La publicidad en la era digital - Evoca
La publicidad en la era digital - EvocaLa publicidad en la era digital - Evoca
La publicidad en la era digital - Evoca
 
Miguel Valls - MED-SV Cleantech Fund - Stanford Jan410
Miguel Valls - MED-SV Cleantech Fund - Stanford Jan410Miguel Valls - MED-SV Cleantech Fund - Stanford Jan410
Miguel Valls - MED-SV Cleantech Fund - Stanford Jan410
 
Plm fi d_qm_2002
Plm fi d_qm_2002Plm fi d_qm_2002
Plm fi d_qm_2002
 
2010 Pep Talk Presentation
2010 Pep Talk Presentation2010 Pep Talk Presentation
2010 Pep Talk Presentation
 
Formatos educativos Cs Ns JBA
Formatos educativos   Cs Ns JBAFormatos educativos   Cs Ns JBA
Formatos educativos Cs Ns JBA
 
Telco sector deck (Private Life of Mail)
Telco sector deck (Private Life of Mail)Telco sector deck (Private Life of Mail)
Telco sector deck (Private Life of Mail)
 
Marketing Informatico (diapositiva)
Marketing Informatico (diapositiva)Marketing Informatico (diapositiva)
Marketing Informatico (diapositiva)
 
Códigos QR en Turismo
Códigos QR en TurismoCódigos QR en Turismo
Códigos QR en Turismo
 
Master mind de negocios e inglés
Master mind de negocios e inglésMaster mind de negocios e inglés
Master mind de negocios e inglés
 
El bosque animado
El bosque animadoEl bosque animado
El bosque animado
 
Porque estudiar Arquitectura???
Porque estudiar Arquitectura???Porque estudiar Arquitectura???
Porque estudiar Arquitectura???
 
Ecuaciones diofánticas 02
Ecuaciones diofánticas 02Ecuaciones diofánticas 02
Ecuaciones diofánticas 02
 
G Feismic Dafety Of Rchools Repal
G Feismic Dafety Of Rchools RepalG Feismic Dafety Of Rchools Repal
G Feismic Dafety Of Rchools Repal
 

Más de Krasimir Berov (Красимир Беров) (16)

Хешове
ХешовеХешове
Хешове
 
Списъци и масиви
Списъци и масивиСписъци и масиви
Списъци и масиви
 
Скаларни типове данни
Скаларни типове данниСкаларни типове данни
Скаларни типове данни
 
Въведение в Perl
Въведение в PerlВъведение в Perl
Въведение в Perl
 
System Programming and Administration
System Programming and AdministrationSystem Programming and Administration
System Programming and Administration
 
Network programming
Network programmingNetwork programming
Network programming
 
Processes and threads
Processes and threadsProcesses and threads
Processes and threads
 
Working with databases
Working with databasesWorking with databases
Working with databases
 
Working with text, Regular expressions
Working with text, Regular expressionsWorking with text, Regular expressions
Working with text, Regular expressions
 
Subroutines
SubroutinesSubroutines
Subroutines
 
IO Streams, Files and Directories
IO Streams, Files and DirectoriesIO Streams, Files and Directories
IO Streams, Files and Directories
 
Syntax
SyntaxSyntax
Syntax
 
Hashes
HashesHashes
Hashes
 
Lists and arrays
Lists and arraysLists and arrays
Lists and arrays
 
Scalar data types
Scalar data typesScalar data types
Scalar data types
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 

Último

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAnitaRaj43
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 

Último (20)

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

Packages, modules, classes and objects

  • 1. Perl Programming Course Packages, modules, classes and objects Krassimir Berov I-can.eu
  • 2. Contents 1. What is a module? 2. What is a package? 3. What is a class? 4. What is an object? 5. Working with objects • bless and ref • tie and tied • use and require 6. Using Modules 7. Creating a module
  • 3. What is a module? • A module is just a set of related functions and variables in a library file • ...a Perl package with the same name as the file. • It is specifically designed to be reusable by other modules or programs • May provide mechanism for exporting some of its symbols into the symbol table of any package using it • May function as a class definition and make its semantics available implicitly through method calls on the class and its objects • See Exporter and perlmodlib
  • 4. What is a package? • package NAMESPACE • declares the compilation unit as being in the given namespace • The scope of the package declaration is from the declaration itself through the end of the enclosing block, file, or eval (the same as the my operator) • Refer to things in other packages by prefixing the identifier with the package name and a double colon: $Package::Variable • See perlfunc/package, perlmod/Packages package Human; our $legs = 2; our $hands = 2;
  • 5. What is a class? • There is no special class syntax in Perl • A package acts as a class if it provides subroutines to act as methods • A class may be thought as a user-defined type. • use base to both load the base classes (packages) and inherit from them • A class should provide one or more ways to generate objects package Dog; use base qw(Mammal); sub new { my $class = shift; my $self = {}; bless $self, $class; }
  • 6. What is an object? • An Object is Simply a Reference with user-defined type • Perl doesn't provide any special syntax for constructors • A Method is simply a Subroutine • A method expects its first argument to be the object (reference) or package (string) it is being invoked on • A constructor is a subroutine that returns a reference to something "blessed" into a class • Constructors are often class methods • You could think of the method call as just another form of dereferencing
  • 7. Working with objects • bless REF,CLASSNAME bless REF • tells the thingy referenced by REF that it is now an object in the CLASSNAME package and returns the reference • If CLASSNAME is omitted, the current package is used • NOTE: Always use the two-argument version to enable inheritance Make sure that CLASSNAME is a true value
  • 8. Working with objects • bless - Example: #bless.pl { package Dog; sub new { my $class = shift; my $self = { name =>'Puffy', nationality =>'bg_BG', }; bless $self, $class; } sub name { return $_[0]->{name} } #... }
  • 9. Working with objects • ref EXPR ref Returns a non-empty string if EXPR is a reference, the empty string otherwise. • If EXPR is not specified, $_ will be used. • The value returned depends on the type of thing the reference is a reference to. • Builtin types include: SCALAR, ARRAY, HASH, CODE, REF, GLOB, LVALUE, FORMAT, IO, Regexp • If the referenced object has been blessed into a package, then that package name is returned instead. • You can think of ref as a typeof operator. • See ref.pl for MORE.
  • 10. Working with objects • tie VARIABLE,CLASSNAME,LIST • binds a variable to a package class that will provide the implementation for the variable • VARIABLE is the name of the variable to be tied • CLASSNAME is the name of a class implementing objects of correct type • Any additional arguments are passed to the new method of the class (meaning TIESCALAR , TIEHANDLE , TIEARRAY , or TIEHASH ) • See perlfunc/tied, perltie, Tie::Hash, Tie::Array, Tie::Scalar, and Tie::Handle • See DB_File or the Config module for interesting tie implementations. See also tie.pl for EXAMPLE
  • 11. Working with objects • tied VARIABLE • Returns a reference to the object underlying VARIABLE • The same value was originally returned by the tie call that bound the variable to a package. • Returns the undefined value if VARIABLE isn't tied to a package. • See tie.pl and tied.pl for examples
  • 12. Working with objects • use Module VERSION LIST use Module use VERSION • It is exactly equivalent to BEGIN { require Module; Module->import( LIST ); } • The BEGIN forces the require and import to happen at compile time. • import imports the list of features into the current package • If no import method can be found, the call is skipped • In use VERSION form VERSION has to be a numeric argument such as 5.016, which will be compared to $]
  • 13. Working with objects • require VERSION require EXPR require • demands that a library file be included if it hasn't already been included • The file is included via the do-FILE mechanism, • Lexical variables in the invoking script will be invisible to the included code. • The file must return true as the last statement to indicate successful execution of any initialization code • If EXPR is a bareword, the require assumes a ".pm" extension and replaces "::" with "/" in the filename
  • 14. Using Modules • See If you have what you need in CORE modules or get the module you need using ppm berov@berov:~> ppm
  • 15. Using Modules • Example #using_modules.pl use strict; use warnings; use utf8; use FindBin; BEGIN { $ENV{APP_ROOT} = $FindBin::Bin .'/..'; } use lib($ENV{APP_ROOT}.'/lib'); use Data::Table;#patched... See TODO in module use Data::Dumper; ...
  • 16. Packages, modules, classes and objects • Ressources • Beginning Perl (Chapter 11 – Object-Oriented Perl) • perlboot - Beginner's Object-Oriented Tutorial • perlobj - Perl objects • perltoot - Tom's object-oriented tutorial for perl • perltooc - Tom's OO Tutorial for Class Data in Perl • perlbot - Bag'o Object Tricks (the BOT)
  • 17. Packages, modules, classes and objects Questions?