This document provides an overview of object-oriented programming concepts and Moose, a object system for Perl 5. It covers introducing OOP, the basics of classes, objects, methods and attributes. It then discusses Moose specifically, including declaring classes and attributes, subclasses, and best practices. The goal is to provide an introduction to OO programming in Perl using Moose.
Part 1 of "Introduction to Catalyst" talks about installing Catalyst, creating your first application, examining its structure, and how HTTP requests are dispatched.
Part 1 of "Introduction to Catalyst" talks about installing Catalyst, creating your first application, examining its structure, and how HTTP requests are dispatched.
Structured Query Language
SQL Commands:
• The standard SQL commands to interact with relational databases are CREATE, SELECT, INSERT, UPDATE, DELETE and DROP
In this slides discuss about the short introduction about Structured query language .. this slides is help for those students those study database relevant
Function in PL/SQL, Create Function Syntax, Example – No Parameters in Function , Example – Testing RetrieveSalary Function, Example Function with Parameter, Dropping a Function
In this chapter we will learn about arrays as a way to work with sequences of elements of the same type. We will explain what arrays are, how we declare, create, instantiate and use them. We will examine one-dimensional and multidimensional arrays. We will learn different ways to iterate through the array, read from the standard input and write to the standard output. We will give many example exercises, which can be solved using arrays and we will show how useful they really are.
Inheritance In C++ (Object Oriented Programming)
Basically this presentation is about inheritance in C++. Whole Inheritance of C++ is described in it in very well way.
Oracle 19c Database AdministrationOracle Database 19c is the final, and therefore 'long term support' releaseof the Oracle Database 12c family of products (which includes Oracle Database 18c). Oracle Database 19c builds upon the innovations of previous releases such as Multitenant, In-Memory, JSON support, Sharding and many other features that enable Oracle✔8217;s Autonomous Database Cloud Services. This latest release of the world✔8217;s most popular database also introduces new functionality, providing customers with a multi-model enterprise-class database for all their typical use cases.This Book provides detailed information on the architecture of an Oracle Database instance and database, enabling you to effectively manage your database resources. You learn how to create database storage structures appropriate for the business applications supported by your database. In addition, you learn how to create users and administer database security to meet your business requirements. Basic information on backup and recovery techniques is presented in this course. To provide an acceptable response time to users and manage resources effectively, you learn how to monitor your database and manage performance.
Structured Query Language
SQL Commands:
• The standard SQL commands to interact with relational databases are CREATE, SELECT, INSERT, UPDATE, DELETE and DROP
In this slides discuss about the short introduction about Structured query language .. this slides is help for those students those study database relevant
Function in PL/SQL, Create Function Syntax, Example – No Parameters in Function , Example – Testing RetrieveSalary Function, Example Function with Parameter, Dropping a Function
In this chapter we will learn about arrays as a way to work with sequences of elements of the same type. We will explain what arrays are, how we declare, create, instantiate and use them. We will examine one-dimensional and multidimensional arrays. We will learn different ways to iterate through the array, read from the standard input and write to the standard output. We will give many example exercises, which can be solved using arrays and we will show how useful they really are.
Inheritance In C++ (Object Oriented Programming)
Basically this presentation is about inheritance in C++. Whole Inheritance of C++ is described in it in very well way.
Oracle 19c Database AdministrationOracle Database 19c is the final, and therefore 'long term support' releaseof the Oracle Database 12c family of products (which includes Oracle Database 18c). Oracle Database 19c builds upon the innovations of previous releases such as Multitenant, In-Memory, JSON support, Sharding and many other features that enable Oracle✔8217;s Autonomous Database Cloud Services. This latest release of the world✔8217;s most popular database also introduces new functionality, providing customers with a multi-model enterprise-class database for all their typical use cases.This Book provides detailed information on the architecture of an Oracle Database instance and database, enabling you to effectively manage your database resources. You learn how to create database storage structures appropriate for the business applications supported by your database. In addition, you learn how to create users and administer database security to meet your business requirements. Basic information on backup and recovery techniques is presented in this course. To provide an acceptable response time to users and manage resources effectively, you learn how to monitor your database and manage performance.
This is the first set of slightly updated slides from a Perl programming course that I held some years ago for the QA team of a big international company.
I want to share it with everyone looking for intransitive Perl-knowledge.
The updates after 1st of June 2014 are made with the kind support of Chain Solutions (http://chainsolutions.net/)
A table of content for all presentations can be found at i-can.eu.
The source code for the examples and the presentations in ODP format are on https://github.com/kberov/PerlProgrammingCourse
4. Use the AM for posting within scientific collaboration networks (SCNs). For a detailed description of our policy on posting to SCNs, please see our Web Posting Guidelines (https://publishing.aip.org/authors/web-posting-guidelines).
5. Reprint the Version of Record (VOR) in print collections written by the Author, or in the Author’s thesis or dissertation. It is understood and agreed that the thesis or dissertation may be made available electronically on the university’s site or in its repository and that copies may be offered for sale on demand.
6. Reproduce copies of the VOR for courses taught by the Author or offered at the institution where the Author is employed, provided no fee is charged for access to the Work.
7. Use the VOR for internal training and noncommercial business purposes by the Author’s employer.
8. Use the VOR in oral presentations made by the Author, such as at conferences, meetings, seminars, etc., provided those receiving copies are informed that they may not further copy or distribute the Work.
9. Distribute the VOR to colleagues for noncommercial scholarly use, provided those receiving copies are informed that they may not further copy or distribute the Work.
10. Post the VOR to their personal web page or their employer’s web page 12 months after publication by AIP Publishing.
11. Deposit the VOR in an institutional or funder-designated repository 12 months after publication by AIP Publishing.
12. Update a prior posting with the VOR on a noncommercial server such as arXiv, 12 months after publication by AIP Publishing.
Author Warranties
Each Author and Copyright Owner represents and warrants to AIP Publishing the following:
1. The Work is the original independent creation of each Author and does not infringe any copyright or violate any other right of any third party.
2. The Work has not been previously published and is not being considered for publication elsewhere in any form, except as a preprint on a noncommercial server such as arXiv, or in a thesis or dissertation.
3. Written permission has been obtained for any material used from other sources and copies of the permission grants have been supplied to AIP Publishing to be included in the manuscript file.
4. All third-party material for which permission has been obtained has been properly credited within the manuscript.
5. In the event that the Author is subject to university open access policies or other institutional restrictions that conflict with any of the rights or provisions of this License, such Author has obtained the necessary waiver from his or her university or institution.
This License must be signed by the Author(s) and, in the case of a Work Made for Hire, also by the Copyright Owners. One Author/Copyright Owner may sign on behalf of all the contributors/owners only if they all have authorized the signing, approved of the License, and agreed to be bound by it. The signing Author and, in the case of a Work Made for Hire, the signing Copyright Owne
Ruby object model - Understanding of object play role for rubyTushar Pal
This is including the Ruby Object Model Detail In which It consist a Hierarchy of Ruby Object.
This PPT Basically will solve Which Class is having which methods ?
Which Module are included or excluded ?
How a Class Work?
Role of Self?
Use of Instance ,Class Variable and Methods
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...Sagar Verma
OOPS and its application in Java, Super class AND This Keyword,Java Bean, POJO ,Memory management in Java ,Packages ,Miscellaneous (Var-Args, toString(), Double equals operator(==))
A (not entirely serious) talk that I gave at the London Perl Mongers technical meeting in March 2018.
It talks about how and why I build a web site listing the line of succession to the British throne back through history.
Does what it says on the tin. An introduction to Modern Perl programming aimed at programmers who have little or no experience in Perl.
I gave this course at the London Perl Workshop in November 2013.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofsAlex Pruden
This paper presents Reef, a system for generating publicly verifiable succinct non-interactive zero-knowledge proofs that a committed document matches or does not match a regular expression. We describe applications such as proving the strength of passwords, the provenance of email despite redactions, the validity of oblivious DNS queries, and the existence of mutations in DNA. Reef supports the Perl Compatible Regular Expression syntax, including wildcards, alternation, ranges, capture groups, Kleene star, negations, and lookarounds. Reef introduces a new type of automata, Skipping Alternating Finite Automata (SAFA), that skips irrelevant parts of a document when producing proofs without undermining soundness, and instantiates SAFA with a lookup argument. Our experimental evaluation confirms that Reef can generate proofs for documents with 32M characters; the proofs are small and cheap to verify (under a second).
Paper: https://eprint.iacr.org/2023/1886
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
Removing Uninteresting Bytes in Software FuzzingAftab Hussain
Imagine a world where software fuzzing, the process of mutating bytes in test seeds to uncover hidden and erroneous program behaviors, becomes faster and more effective. A lot depends on the initial seeds, which can significantly dictate the trajectory of a fuzzing campaign, particularly in terms of how long it takes to uncover interesting behaviour in your code. We introduce DIAR, a technique designed to speedup fuzzing campaigns by pinpointing and eliminating those uninteresting bytes in the seeds. Picture this: instead of wasting valuable resources on meaningless mutations in large, bloated seeds, DIAR removes the unnecessary bytes, streamlining the entire process.
In this work, we equipped AFL, a popular fuzzer, with DIAR and examined two critical Linux libraries -- Libxml's xmllint, a tool for parsing xml documents, and Binutil's readelf, an essential debugging and security analysis command-line tool used to display detailed information about ELF (Executable and Linkable Format). Our preliminary results show that AFL+DIAR does not only discover new paths more quickly but also achieves higher coverage overall. This work thus showcases how starting with lean and optimized seeds can lead to faster, more comprehensive fuzzing campaigns -- and DIAR helps you find such seeds.
- These are slides of the talk given at IEEE International Conference on Software Testing Verification and Validation Workshop, ICSTW 2022.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
Welcome to the first live UiPath Community Day Dubai! Join us for this unique occasion to meet our local and global UiPath Community and leaders. You will get a full view of the MEA region's automation landscape and the AI Powered automation technology capabilities of UiPath. Also, hosted by our local partners Marc Ellis, you will enjoy a half-day packed with industry insights and automation peers networking.
📕 Curious on our agenda? Wait no more!
10:00 Welcome note - UiPath Community in Dubai
Lovely Sinha, UiPath Community Chapter Leader, UiPath MVPx3, Hyper-automation Consultant, First Abu Dhabi Bank
10:20 A UiPath cross-region MEA overview
Ashraf El Zarka, VP and Managing Director MEA, UiPath
10:35: Customer Success Journey
Deepthi Deepak, Head of Intelligent Automation CoE, First Abu Dhabi Bank
11:15 The UiPath approach to GenAI with our three principles: improve accuracy, supercharge productivity, and automate more
Boris Krumrey, Global VP, Automation Innovation, UiPath
12:15 To discover how Marc Ellis leverages tech-driven solutions in recruitment and managed services.
Brendan Lingam, Director of Sales and Business Development, Marc Ellis
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Accelerate your Kubernetes clusters with Varnish Caching
Introduction to OO Perl with Moose
1. Introduction to
OO Perl
With Moose
Dave Cross
Magnum Solutions Ltd
dave@mag-sol.com
2. What We Will Cover
Introduction to Object Oriented
programming
Overview of Moose
Object Attributes
Subclasses
Further information
London Perl Workshop
24th November 2012 2
4. What is OOP?
“Traditional” programming is procedural
Subroutines work on variables
my $twelve = regenerate($eleven);
Variables are dumb
Just stores for data
London Perl Workshop
24th November 2012 4
5. What is OOP?
Object Oriented programming inverts this
Variables are objects
Objects can carry out certain processes
Called methods
my $twelve = $eleven->regenerate();
Objects are intelligent
Objects know what methods they can carry
out
London Perl Workshop
24th November 2012 5
6. Some Concepts
A Class is a type of intelligent variable
e.g. Time Lord
An Object is an instance of a class
e.g. The Doctor
A Method is an action that an object does
e.g. Regenerate
An Attribute is a piece of data in an object
e.g. Name
London Perl Workshop
24th November 2012 6
7. Some Concepts
A class contains a number of methods
An object is of a particular class
The class defines the behaviour of an object
An object has many attributes
A class can also have attributes
London Perl Workshop
24th November 2012 7
8. Methods
Methods can be either class methods or
object methods
Class methods are called on a class
my $doctor = TimeLord->new;
Object methods are called on an object
$doctor->regenerate;
London Perl Workshop
24th November 2012 8
9. Constructors
All classes need a constructor method
Creates a new object of that class
Usually a class method
Often called new
my $doctor = TimeLord->new;
London Perl Workshop
24th November 2012 9
10. Constructors
A Class might have multiple constructors
my $doctor = TimeLord->new;
my $flesh_dr =
TimeLord->clone($doctor);
A constructor might be an object method
my $flesh_dr = $doctor->clone;
London Perl Workshop
24th November 2012 10
11. Accessors & Mutators
Access object attributes with an accessor
method
say “The time lord's name is “,
$doctor->get_name;
Change an attribute with a mutator method
$doctor->set_age(
$doctor->get_age + 1
);
London Perl Workshop
24th November 2012 11
12. Accessor/Mutators
Accessors and mutators are often the same
method
say “The time lord's name is “,
$doctor->name;
$doctor->age($doctor->age + 1);
Checks number of parameters
Reacts appropriately
London Perl Workshop
24th November 2012 12
13. Accessor/Mutators
Which to choose?
Perl Best Practices says get_foo/set_foo
I like one method called foo
No firm rules
Pick one
Stick with it
London Perl Workshop
24th November 2012 13
14. Subclasses
A subclass is a specialisation of a class
“Alien” is a class
“Dalek” is one possible subclass
Avoid reimplementing shared methods
London Perl Workshop
24th November 2012 14
16. OO Perl
Three rules of OO Perl
A class is a package
An object is reference
A method is a subroutine
London Perl Workshop
24th November 2012 16
17. A Class is a Package
Same as any other package
Contains subroutines
Methods
Contains variables
Class attributes
London Perl Workshop
24th November 2012 17
18. An Object is a Reference
Usually a reference to a hash
Hash keys are attribute names
Hash values are attribute values
Actually a “blessed” hash
So it knows what class it is
London Perl Workshop
24th November 2012 18
19. A Method is a Subroutine
Just like any other subroutine
Some rules on parameters
First parameter is class name or object
reference
Some differences in calling
Arrow notation
$doctor->name()
London Perl Workshop
24th November 2012 19
20. Simple Class
package Alien;
sub new {
my ($class, $name) = @_;
my $self = { name => $name };
return bless $self, $class;
}
London Perl Workshop
24th November 2012 20
21. Simple Class
sub name {
my ($self, $name) = @_;
if (defined $name) {
$self->{name} = $name;
}
return $self->{name};
}
1;
London Perl Workshop
24th November 2012 21
22. Using Our Class
use Alien;
my $alien = Alien->new('Mork');
say $alien->name; # prints Mork
$alien->name('Mork from Ork');
say $alien->name;
# prints Mork from Ork
London Perl Workshop
24th November 2012 22
24. Moose
Moose is a Modern Object System for Perl 5
Based on Perl 6 object system
More powerful
More flexible
Easier
London Perl Workshop
24th November 2012 24
25. Simple Moose Class
package Alien;
use Moose;
has name => (
is => 'rw',
isa => 'Str',
);
no Moose;
__PACKAGE__->meta->make_immutable;
London Perl Workshop
24th November 2012 25
26. What's Going On?
use Moose;
Loads Moose environment
Makes our class a subclass of Moose::Object
Turns on use strict and use warnings
London Perl Workshop
24th November 2012 26
27. Declarative Attributes
has name => (
is => 'rw',
isa => 'Str',
);
Creates an attribute called 'name'
Makes it read/write
Must be a string
London Perl Workshop
24th November 2012 27
28. Read/Write Attributes
Moose creates method to access/alter
attributes
$alien->name('Strax');
say $alien->name;
The 'is' property controls how they work
'rw' : read and write
'ro' : read only
London Perl Workshop
24th November 2012 28
29. Private Attributes
Use is => 'bare' for attributes that aren't
readable
No methods are created
Direct hash access
$alien->{name} =
'Commander Strax';
London Perl Workshop
24th November 2012 29
30. Housekeeping
Moose classes carry a lot of baggage
We can (and should) turn some of it off
no Moose;
Remove Moose exports from your namespace
See also namespace::autoclean
__PACKAGE__->meta->make_immutable;
No more changes to class definition
Performance improvements
London Perl Workshop
24th November 2012 30
31. Using Our Class
From the user's perspective, nothing changes
Use it just like other Perl classes
use Alien;
my $strax = Alien->new(
name => 'Strax'
);
say $strax->name;
Named parameters are good
London Perl Workshop
24th November 2012 31
33. Subclassing
A subclass is a specialisation of a superclass
More specific behaviour
New attributes
New methods
Overriding superclass methods
London Perl Workshop
24th November 2012
34. Subclassing
Not all aliens are the same
package Dalek;
use Moose;
extends 'Alien';
has accuracy => (
isa => 'Num',
is => 'rw',
);
London Perl Workshop
24th November 2012
35. Subclassing
sub exterminate {
my $self = shift;
say “EX-TERM-IN-ATE”;
if (rand < $self->accuracy) {
say “$_[0] has been exterminated”;
return 1;
} else {
return;
}
}
London Perl Workshop
24th November 2012
36. Using Subclasses
use Dalek;
my $karn = Dalek->new(
name => 'Karn', accuracy => 0.9,
);
say $karn->name;
$karn->exterminate('The Doctor');
London Perl Workshop
24th November 2012
37. Overriding Methods
Daleks have a different way of using names
A Dalek's name is always “Dalek
Something”
Need to override the name method from
Alien
But we still want to get the name itself from
Alien's method
London Perl Workshop
24th November 2012
38. Method Modifiers
Moose has a declarative way to modify
methods from your superclass
before : run this code before the superclass
method
after : run this code after the superclass
method
around : run this code around the superclass
method
London Perl Workshop
24th November 2012
39. Dalek Names
around name => sub {
my $orig = shift;
my $class = shift;
return 'Dalek ' .
$class->$orig(@_);
};
London Perl Workshop
24th November 2012
41. Declarative Attributes
Attributes are declared in a class using the
has keyword
This is different to “classic” Perl OO
Where attributes are created by the presence of
accessor methods
Attributes have a number of properties
Properties define the attribute
London Perl Workshop
24th November 2012
42. Properties
has name => (
isa => 'Str',
is => 'rw',
);
'isa' and 'is' are properties
Many other options exist
London Perl Workshop
24th November 2012
43. is
is : defines if you can read or write the
attribute
Actually defines whether accessor method is
created
And how it works
$obj->ro_attr('Some value');
“Cannot assign a value to a read-only
accessor”
Use is => 'bare' for private attributes
No accessor created
London Perl Workshop
24th November 2012
44. Accessor Name
“is” is actually a shortcut for two other
properties
reader and writer
has name => (
reader => 'get_name',
writer => 'set_name',
);
London Perl Workshop
24th November 2012
45. Accessor Name
Now we don't have a method called name
say $obj->name; # Error
Need to use get_name
say $obj->get_name;
And set_name
$obj->set_name('New Name');
London Perl Workshop
24th November 2012
46. Best Practices
What is best practice
One method (name)
Two methods (get_name, set_name)
Who cares?
Choose one
And stick with it
Perl Best Practices says two methods
See MooseX::FollowPBP
London Perl Workshop
24th November 2012
47. Required Attributes
By default Moose attributes are optional
Make them mandatory with required
has name => (
required => 1,
);
my $alien = Alien->new;
“Attribute (name) is required at constructor
Alien::new”
London Perl Workshop
24th November 2012
48. Attribute Defaults
Set a default for missing attributes
has accuracy => (
default => 0.5,
);
Or a subroutine reference
has accuracy => (
default => sub { rand },
);
London Perl Workshop
24th November 2012
49. Attribute Builder
Define a builder method instead of a default
subroutine
has accuracy => (
builder => '_build_accuracy',
);
sub _build_accuracy {
return rand;
}
Easier to subclass
London Perl Workshop
24th November 2012
50. Attribute Types
Set the type of an attribute with isa
has accuracy => (
isa => 'Num',
);
Validation checks run as value is set
London Perl Workshop
24th November 2012
51. Defining Types
Accuracy should be less than 1
To give the Doctor a chance
Define your own type
subtype 'Accuracy'
=> as 'Num'
=> where { $_ < 1 };
London Perl Workshop
24th November 2012
52. Using Types
has accuracy => (
isa => 'Accuracy',
);
my $dalek = Dalek->new(
accuracy => 1
);
“Attribute (accuracy) does not pass the type
constraint because: Validation failed for
'Accuracy' with value 1 at constructor
Dalek::new”
London Perl Workshop
24th November 2012
53. Aggregate Attributes
You can define aggregate attributes
isa => 'ArrayRef'
Reference to array (elements are any type)
isa => 'ArrayRef[Int]'
Reference to array (elements are integers)
London Perl Workshop
24th November 2012
54. Array Example
Daleks like to keep track of their victims
has victims (
is => 'rw',
isa => 'ArrayRef[Str]',
default => sub { [] },
);
And in the exterminate method
push $self->victims, $_[0];
London Perl Workshop
24th November 2012
55. Array Example
sub brag {
my $self = shift;
if (@{$self->victims}) {
say $self->name, ' has killed ',
scalar @{$self->victims},
' enemies of the Daleks';
say 'Their names are: ',
join(', ',
@{$self->victims});
} else {
say $self->name,
' has nothing to brag about';
}
}
London Perl Workshop
24th November 2012
56. Hash Attributes
Moose also supports hash ref attributes
has some_attribute => (
isa => 'HashRef[Str]',
is => 'rw',
);
London Perl Workshop
24th November 2012
57. More Types
Attributes can also be objects
has useragent => (
is => 'rw',
isa => 'LWP::UserAgent',
);
Or a union of types
has output => (
is 'rw',
isa => 'Object | Filehandle',
);
London Perl Workshop
24th November 2012
58. Lazy Attributes
Some attributes are rarely used
And can be complex to construct
It's a waste of resources to build them before
they are needed
Mark them as lazy
And define a build method
London Perl Workshop
24th November 2012 58
59. Lazy Attributes
has useragent => (
is => 'LWP::UserAgent',
lazy => 1,
builder => '_build_ua',
);
sub _build_ua {
return LWP::UserAgent->new(...);
}
$self->useragent->get(...);
# creates object
London Perl Workshop
24th November 2012 59
60. Triggers
A trigger is a subroutine that is called when
an attribute's value changes
Subroutine is passed the old and new values
has name => (
trigger => &name_change,
);
sub name_change {
my ($self, $new, $old) = @_;
warn
“Name changed from $old to $new”;
}
London Perl Workshop
24th November 2012 60
62. Constructors
A constructor is a special type of method
It is usually a class method
It returns a new object
Moose classes prefer named parameters
my $karn = Dalek->new(
name => 'Karn', accuracy => 0.99,
);
London Perl Workshop
24th November 2012 62
63. Default Constructor
The default Moose constructor builds an
object from its parameters
Checks for mandatory attributes
Checks type constraints
Returns an object
London Perl Workshop
24th November 2012 63
64. Different Behaviour
Some constructors need to do other
processing
Not just build an object
Sometimes it's convenient not to use named
parameters
Use BUILD and BUILDARGS to override
Moose's default behaviour
London Perl Workshop
24th November 2012 64
65. BUILDARGS
More flexible parameters
Take a parameter list convert it to named
parameters
Commonly Daleks only need a name
my $karn = Dalek->new(
name => 'Karn'
);
Why not simplify?
my $karn = Dalek->new('Karn');
London Perl Workshop
24th November 2012 65
66. Dalek Construction
We can use BUILDARGS to build a list of
named parameters
around BUILDARGS => sub {
my $orig = shift;
my $class = shift;
if (@_ == 1 and !ref $_[0]) {
return
$class->$orig({name => $_[0]});
} else {
return $class->$orig(@_);
}
}
London Perl Workshop
24th November 2012 66
67. Announcing Your Dalek
When a new Dalek is created we want to
announce its name
We can use the BUILD method
After a new object is constructed, the
BUILD method is called
Use it to carry out any additional processing
London Perl Workshop
24th November 2012 67
68. BUILD Example
sub BUILD {
my $self = shift;
say $self->name . ' is born.';
}
This method is called every time a new
Dalek object is created
Called after the object is constructed
But before the new method returns
London Perl Workshop
24th November 2012 68
70. More Moose
Moose does a lot more
We have only scratched the surface
Good documentation
CPAN
Add-on modules
MooseX::*
London Perl Workshop
24th November 2012 70
71. More Moose
Type hierarchy
Type coercion
Method modifiers
Method delegation
Overriding attributes
Roles and traits
Meta programming
London Perl Workshop
24th November 2012 71
72. Perl School
Object Oriented Programming with Perl
and Moose
8th December
Google Campus, London
Full day course
£30
http://perlschool.co.uk/
London Perl Workshop
24th November 2012 72