SlideShare una empresa de Scribd logo
1 de 22
Descargar para leer sin conexión
Perl Objects 101
Simple OOP with Perl
Terms
Class - a template describing data and
behavior specific to the object
Object - a container for “some data” which is
associated with “some behavior”
Method - a function associated with a class
Attribute - private data associated with each
unique object
Perl Terms
Class - a package containing methods
Object - a reference with an associated class
Method - a subroutine which takes an object
or class as its first argument
Attribute - any sort of Perl data should work
Bless = magic
bless $reference, Classname

is any reference (scalar, hash, array,
function, file handle)
Classname is any package name.
$reference

The result is a blessed reference; an object.
Methods
Methods are subs defined in the class’s
package.
Call them using the dereferencing arrow:
$obj->method( $param1, $param2 );

The first parameter will be an object reference.
Accessing the data
Since the object is still a reference, the
underlying data are easily accessible.
$obj->{attr1} = 42;
No Protection
What you just saw is considered BAD.
Any code outside of the class can easily tinker
with the insides of the object.
Class Methods
Same syntax to call Class methods:
$my_class->method();

Except the package name is used instead of the
object reference.
Constructors
Constructors are class methods that return an
object.
The name is arbitrary, although new() is most
commonly used.
package MyClass;
sub new {
bless { attr1 => 42 }, ‘MyClass’;
}
Better Constructor
It’s first parameter will normally be the class
name.
package MyClass;
sub new {
my ( $class ) = @_;
bless { attr1 => 42 }, $class;
}
Inheritance
@ISA array
It is a package global.
package MyInheritedClass;
use vars qw( @ISA );
@ISA = qw( MyClass );
sub my_method2 {};
@ISA Continued
When an object or class method is called, Perl
gets the package and tries to find a sub in that
package with the same name as the method.
If found, it calls that.
If not, it looks up the @ISA array for other
packages, and tries to find the method in those.
UNIVERSAL
All classes implicitly inherit from class
“UNIVERSAL” as their last base class.
Inheriting Shortcut
This is tedious:
use vars qw(@ISA);
@ISA = qw(MyClass);

There is a shortcut:
use base ‘MyClass’;
Calling Inherited Methods
We can do:
package MyInheritedClass;
sub method1 {
my ( $self ) = @_;
MyClass::method1($self);
}

That’s not OOish and won’t work if MyClass
doesn’t have a sub method1.
SUPER Pseudo-Class
The right thing would be to do:
package MyInheritedClass;
sub method1 {
my ( $self ) = @_;
$self->SUPER::method1($self);
}
Inheriting Constructors
Normally, a base class constructor will bless the
reference into the correct class, so we just need
to do some initialization:
package MyInheritedClass;
sub new {
my ( $class, %params ) = @_;
my $self = $class->SUPER::new(%params);
# do something with the params here...
return $self;
}

Mostly, such constructors are not needed.
Destructors
Perl has automatic garbage collection, so
mostly, destructors aren’t needed.
If they are, create a sub called DESTROY:
sub DESTROY {
my ($self) = @_;
# free some resources
}
Multiple Inheritance
Just put more stuff into @ISA
@ISA = qw(Class1, Class2);

or
use base qw(Class1 Class2);
Data Storage for Objects
Most objects use hashrefs.
Convenient to use.
No protection.
You can’t prevent code from tinkering.
Well, there is a thing called “Inside Out
Objects”, but we won’t cover that today.
Other ways of OOP
Many, many modules have been created to help
with this.
Currently, Moo/Mouse/Moose is The One True
Way
This is Perl, so you know that isn’t quite true.
Let’s look at
...some code.

Más contenido relacionado

La actualidad más candente

Java Chapter 05 - Conditions & Loops: part 7
Java Chapter 05 - Conditions & Loops: part 7Java Chapter 05 - Conditions & Loops: part 7
Java Chapter 05 - Conditions & Loops: part 7
DanWooster1
 
Object oriented programming in php
Object oriented programming in phpObject oriented programming in php
Object oriented programming in php
Aashiq Kuchey
 

La actualidad más candente (20)

Java Collection Framework
Java Collection FrameworkJava Collection Framework
Java Collection Framework
 
9collection in c#
9collection in c#9collection in c#
9collection in c#
 
Array list (java platform se 8 )
Array list (java platform se 8 )Array list (java platform se 8 )
Array list (java platform se 8 )
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 
Java Chapter 05 - Conditions & Loops: part 7
Java Chapter 05 - Conditions & Loops: part 7Java Chapter 05 - Conditions & Loops: part 7
Java Chapter 05 - Conditions & Loops: part 7
 
C# Collection classes
C# Collection classesC# Collection classes
C# Collection classes
 
Dictionaries in Python
Dictionaries in PythonDictionaries in Python
Dictionaries in Python
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
 
Python dictionary
Python dictionaryPython dictionary
Python dictionary
 
Lecture 4 - Object Interaction and Collections
Lecture 4 - Object Interaction and CollectionsLecture 4 - Object Interaction and Collections
Lecture 4 - Object Interaction and Collections
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Generics
GenericsGenerics
Generics
 
Python Programming - V. Sequences (List and Tuples) and Dictionaries
Python Programming - V. Sequences (List and Tuples) and DictionariesPython Programming - V. Sequences (List and Tuples) and Dictionaries
Python Programming - V. Sequences (List and Tuples) and Dictionaries
 
Object oriented programming in php
Object oriented programming in phpObject oriented programming in php
Object oriented programming in php
 
List interface in collections framework
List interface in collections frameworkList interface in collections framework
List interface in collections framework
 
L11 array list
L11 array listL11 array list
L11 array list
 

Destacado (8)

Packaging 4 word new font size
Packaging 4 word new font sizePackaging 4 word new font size
Packaging 4 word new font size
 
Vision
VisionVision
Vision
 
Perl testing 101
Perl testing 101Perl testing 101
Perl testing 101
 
The Dan Cooper Team Experience
The Dan Cooper Team ExperienceThe Dan Cooper Team Experience
The Dan Cooper Team Experience
 
Periodic Table Presentation
Periodic Table Presentation Periodic Table Presentation
Periodic Table Presentation
 
Fyna portafolio ligth version pre
Fyna portafolio ligth version preFyna portafolio ligth version pre
Fyna portafolio ligth version pre
 
Dna structure
Dna structureDna structure
Dna structure
 
Advent Season
Advent SeasonAdvent Season
Advent Season
 

Similar a Perl objects 101

Advanced php
Advanced phpAdvanced php
Advanced php
hamfu
 
PHP-05-Objects.ppt
PHP-05-Objects.pptPHP-05-Objects.ppt
PHP-05-Objects.ppt
rani marri
 
Object-Oriented Programming with Perl and Moose
Object-Oriented Programming with Perl and MooseObject-Oriented Programming with Perl and Moose
Object-Oriented Programming with Perl and Moose
Dave Cross
 
Php object orientation and classes
Php object orientation and classesPhp object orientation and classes
Php object orientation and classes
Kumar
 

Similar a Perl objects 101 (20)

Ruby object model
Ruby object modelRuby object model
Ruby object model
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
OOPs Concept
OOPs ConceptOOPs Concept
OOPs Concept
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
Introduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection APIIntroduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection API
 
Class
ClassClass
Class
 
Java defining classes
Java defining classes Java defining classes
Java defining classes
 
Ruby object model - Understanding of object play role for ruby
Ruby object model - Understanding of object play role for rubyRuby object model - Understanding of object play role for ruby
Ruby object model - Understanding of object play role for ruby
 
FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3
 
Advanced php
Advanced phpAdvanced php
Advanced php
 
Stoop 400 o-metaclassonly
Stoop 400 o-metaclassonlyStoop 400 o-metaclassonly
Stoop 400 o-metaclassonly
 
Reflection and Introspection
Reflection and IntrospectionReflection and Introspection
Reflection and Introspection
 
09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
OOP in PHP.pptx
OOP in PHP.pptxOOP in PHP.pptx
OOP in PHP.pptx
 
Python oop third class
Python oop   third classPython oop   third class
Python oop third class
 
PHP-05-Objects.ppt
PHP-05-Objects.pptPHP-05-Objects.ppt
PHP-05-Objects.ppt
 
Object-Oriented Programming with Perl and Moose
Object-Oriented Programming with Perl and MooseObject-Oriented Programming with Perl and Moose
Object-Oriented Programming with Perl and Moose
 
Php object orientation and classes
Php object orientation and classesPhp object orientation and classes
Php object orientation and classes
 
4Unit - 2 The Object Class.pptx
4Unit - 2 The Object Class.pptx4Unit - 2 The Object Class.pptx
4Unit - 2 The Object Class.pptx
 

Último

+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...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
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
Victor Rentea
 
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
Safe Software
 

Último (20)

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
 
+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...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
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
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
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
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
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, ...
 
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
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
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
 
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
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 

Perl objects 101

  • 1. Perl Objects 101 Simple OOP with Perl
  • 2. Terms Class - a template describing data and behavior specific to the object Object - a container for “some data” which is associated with “some behavior” Method - a function associated with a class Attribute - private data associated with each unique object
  • 3. Perl Terms Class - a package containing methods Object - a reference with an associated class Method - a subroutine which takes an object or class as its first argument Attribute - any sort of Perl data should work
  • 4. Bless = magic bless $reference, Classname is any reference (scalar, hash, array, function, file handle) Classname is any package name. $reference The result is a blessed reference; an object.
  • 5. Methods Methods are subs defined in the class’s package. Call them using the dereferencing arrow: $obj->method( $param1, $param2 ); The first parameter will be an object reference.
  • 6. Accessing the data Since the object is still a reference, the underlying data are easily accessible. $obj->{attr1} = 42;
  • 7. No Protection What you just saw is considered BAD. Any code outside of the class can easily tinker with the insides of the object.
  • 8. Class Methods Same syntax to call Class methods: $my_class->method(); Except the package name is used instead of the object reference.
  • 9. Constructors Constructors are class methods that return an object. The name is arbitrary, although new() is most commonly used. package MyClass; sub new { bless { attr1 => 42 }, ‘MyClass’; }
  • 10. Better Constructor It’s first parameter will normally be the class name. package MyClass; sub new { my ( $class ) = @_; bless { attr1 => 42 }, $class; }
  • 11. Inheritance @ISA array It is a package global. package MyInheritedClass; use vars qw( @ISA ); @ISA = qw( MyClass ); sub my_method2 {};
  • 12. @ISA Continued When an object or class method is called, Perl gets the package and tries to find a sub in that package with the same name as the method. If found, it calls that. If not, it looks up the @ISA array for other packages, and tries to find the method in those.
  • 13. UNIVERSAL All classes implicitly inherit from class “UNIVERSAL” as their last base class.
  • 14. Inheriting Shortcut This is tedious: use vars qw(@ISA); @ISA = qw(MyClass); There is a shortcut: use base ‘MyClass’;
  • 15. Calling Inherited Methods We can do: package MyInheritedClass; sub method1 { my ( $self ) = @_; MyClass::method1($self); } That’s not OOish and won’t work if MyClass doesn’t have a sub method1.
  • 16. SUPER Pseudo-Class The right thing would be to do: package MyInheritedClass; sub method1 { my ( $self ) = @_; $self->SUPER::method1($self); }
  • 17. Inheriting Constructors Normally, a base class constructor will bless the reference into the correct class, so we just need to do some initialization: package MyInheritedClass; sub new { my ( $class, %params ) = @_; my $self = $class->SUPER::new(%params); # do something with the params here... return $self; } Mostly, such constructors are not needed.
  • 18. Destructors Perl has automatic garbage collection, so mostly, destructors aren’t needed. If they are, create a sub called DESTROY: sub DESTROY { my ($self) = @_; # free some resources }
  • 19. Multiple Inheritance Just put more stuff into @ISA @ISA = qw(Class1, Class2); or use base qw(Class1 Class2);
  • 20. Data Storage for Objects Most objects use hashrefs. Convenient to use. No protection. You can’t prevent code from tinkering. Well, there is a thing called “Inside Out Objects”, but we won’t cover that today.
  • 21. Other ways of OOP Many, many modules have been created to help with this. Currently, Moo/Mouse/Moose is The One True Way This is Perl, so you know that isn’t quite true.