SlideShare ist ein Scribd-Unternehmen logo
1 von 17
Downloaden Sie, um offline zu lesen
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?

Weitere ähnliche Inhalte

Andere mochten auch

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
 

Andere mochten auch (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
 

Mehr von 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
 

Kürzlich hochgeladen

Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
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
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 

Kürzlich hochgeladen (20)

Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
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?
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 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?