SlideShare uma empresa Scribd logo
1 de 17
Baixar para ler offline
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?

Mais conteúdo relacionado

Destaque

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
 

Destaque (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
 

Mais 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

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 

Último (20)

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 

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?