The document provides an overview of Modern Perl, covering its syntax changes, core features such as variables, flow control, and subroutines. It discusses various data types including scalars, arrays, and hashes, as well as Perl’s versioning and support cycle. Additionally, it goes into details about control structures, boolean values, comparisons, and the use of subroutines in Perl programming.
Introduction and overview of topics including Modern Perl, its features, variable types, flow control, and object-oriented programming.
Discussion on the definition of Modern Perl, its core syntax changes, and the annual release cycle, including current and upcoming versions.
Overview of Perl features and how it differs from other programming languages including variables, flow control, and subroutines.
Explanation of variable types in Perl (scalars, arrays, hashes), naming conventions, and importance of variable declaration.
Examples of scalar variables, type conversion, quoting strings, and using backslashes in strings.
Undefined values, array variable basics, accessing array elements, slices, and distinguishing between arrays and lists.
Introduction to hash variables, accessing and setting hash values, and use of the default variable.
Flow control in Perl, including Boolean values, comparison operators, and various control structures like if/else, for, and while.
Overview of subroutines in Perl, how arguments are passed, and differences between pass-by-reference and pass-by-value.
Introduction to references including creation, usage, and why references are useful in Perl.
Discussion on scalar and list context, how functions behave differently depending on context.
Introduction to the Comprehensive Perl Archive Network (CPAN), its resources, and module installation.
Overview of powerful CPAN libraries used for object-oriented programming and database access.Details about Perl's OOP capabilities, including Moose framework, creating classes and methods.
Standard tools for database access in Perl, using DBI and the concept of Object-Relational Mapping.
Introduction to Perl web frameworks, importance of frameworks in simplifying web application development.
Introduction to PSGI, its advantages, and how it helps unify various web environments in Perl development.
Summary of resources for further learning, including Perl documentation, user groups, workshops, and conferences.
What is ModernPerl
●
Not well defined
●
Can mean at least two things
●
Changes to core Perl syntax
●
Big additions to Perl's toolset
–
–
DBIx::Class
–
●
Moose
Catalyst
We will cover both
London Perl Workshop
30th November 2013
6.
Perl Releases
●
Annual releasecycle
–
Usually in spring
●
Minor versions when required
●
Even major version is stable
–
●
5.10.x, 5.12.x, 5.14.x, 5.16.x, 5.18.x, etc
Odd major version is development
–
5.9.x, 5.11.x, 5.13.x, 5.15.x, 5.17.x, 5.19.x, etc
London Perl Workshop
30th November 2013
7.
Perl Support
●
Perl ismaintained by volunteers
●
Support resource is limited
●
Official support for two major releases
–
●
Currently 5.16 and 5.18
Support for older releases may be available from
vendors
London Perl Workshop
30th November 2013
Introduction to Perl
●
Quicklook at some Perl features
●
Differences from other languages
●
Variables
●
Flow control
●
Subroutines
●
Context
London Perl Workshop
30th November 2013
11.
Variables in Perl
●
Perlvariables are of three kinds
●
Scalars
●
Arrays
●
Hashes
●
Filehandles and Subroutines can also be treated
like variables
–
But we won't be covering that today
London Perl Workshop
30th November 2013
12.
Perl Variable Types
●
Notthe kind of data they store
–
String, Integer, Float, Boolean
●
The amount of data
●
How it is accessed
London Perl Workshop
30th November 2013
13.
Variable Names
●
●
●
Contain alphanumericcharacters and underscores
User-defined variable names may not start with
numbers
Variable names are preceded by a punctuation
mark indicating the type of data
London Perl Workshop
30th November 2013
14.
Sigils
●
Punctuations marks indicatevariable type
●
Scalars use $
–
●
Arrays use @
–
●
$doctor
@time_lords
Hashes use %
–
%companions
London Perl Workshop
30th November 2013
15.
Declaring variables
●
You don'tneed to declare variables
●
But it's a very good idea
–
–
●
●
●
Typos
Scoping
use strict enforces this
use strict;
my $doctor;
my ($doctor, @time_lords, %companions);
London Perl Workshop
30th November 2013
16.
Scalar Variables
●
●
●
Store asingle item of data
my $name = "Arthur";
my $whoami =
'Just Another Perl Hacker';
●
my $meaning_of_life = 42;
●
my $number_less_than_1 = 0.000001;
●
my $very_large_number = 3.27e17;
# 3.27 times 10 to the power of 17
London Perl Workshop
30th November 2013
17.
Type Conversions
●
●
●
●
●
Perl convertsbetween strings and numbers
whenever necessary
Add int to a floating point number
my $sum = $meaning_of_life +
$number_less_than_1;
Putting a number into a string
print "$name says, 'The meaning of
life is $sum.'n";
London Perl Workshop
30th November 2013
18.
Quoting Strings
●
●
●
●
Single quotesdon't expand variables or escape
sequences
my $price = '$9.95';
Double quotes do
my $invline =
"24 widgets @ $price eachn";
London Perl Workshop
30th November 2013
19.
Backslashes
●
●
●
Use a backslashto escape special characters in
double quoted strings
print "He said "The price is
$300"";
This can look ugly
London Perl Workshop
30th November 2013
20.
Better Quotes
●
●
This isa tidier alternative
print qq(He said "The price is
$300");
●
Also works for single quotes
print q(He said "That's too
expensive");
●
Doesn't need to be brackets
●
London Perl Workshop
30th November 2013
21.
Choose Your Quotes
●
Choosecharacters to use with q() and qq()
●
Brackets
–
–
●
Close with opposite character
q(...), q[...], q{...}, q<...>
Non-brackets
–
–
●
Close with same character
q/.../, q|...|, q+...+, q#...#
Similar rules for many quote-like operators
London Perl Workshop
30th November 2013
22.
Undefined Values
●
A scalarthat hasn't had data put into it will contain
the special value “undef”
●
Test for it with defined() function
●
if (defined($my_var)) { ... }
●
Like NULL in SQL
London Perl Workshop
30th November 2013
23.
Array Variables
●
●
Arrays containan ordered list of scalar values
my @fruit = ('apples', 'oranges',
'guavas', 'passionfruit',
'grapes');
●
my @magic_numbers = (23, 42, 69);
●
Individual elements can be different types
●
my @random_scalars = ('mumble', 123.45,
'dave cross',
-300, $name);
London Perl Workshop
30th November 2013
24.
Array Elements
●
●
●
●
●
Accessing individualelements of an array
print $fruits[0];
# prints "apples"
Note: Indexes start from zero
print $random_scalars[2];
# prints "dave cross"
Note @ changes to $ when accessing single
elements
London Perl Workshop
30th November 2013
25.
Sigil Changes
●
Array sigilchanges from @ to $
●
When accessing individual elements
●
Each element is a scalar
●
Therefore use scalar sigil
●
Similar in English
–
“These elements” vs “This element”
London Perl Workshop
30th November 2013
26.
Array Slices
●
●
●
●
Returns alist of elements from an array
print @fruits[0,2,4];
# prints "apples", "guavas",
# "grapes"
print @fruits[1 .. 3];
# prints "oranges", "guavas",
# "passionfruit"
Note use of @ as we are accessing more than one
element of the array
–
“These elements”
London Perl Workshop
30th November 2013
27.
Setting Array Values
●
$array[4]= 'something';
●
$array[400] = 'something else';
●
Also with slices
@array[4, 7 .. 9] =
('four','seven', 'eight','nine');
●
@array[1, 2] = @array[2, 1];
●
London Perl Workshop
30th November 2013
28.
Array Size
●
●
●
●
$#array isthe index of the last element in
@array
Therefore $#array + 1 is the number of
elements
$count = @array;
Does the same thing and is easier to
understand
London Perl Workshop
30th November 2013
29.
Array vs List
●
Arraysand lists are different
●
Often confused
●
●
●
●
Array is a variable
– @array
List is a data literal
– (1, 2, 3, 4)
Like $scalar vs 'string'
Lists can be stored in arrays
– @array = (1, 2, 3, 4);
London Perl Workshop
30th November 2013
30.
Hash Variables
●
●
●
Hashes implement“look-up tables” or
“dictionaries”
Initialised with a list
%french = ('one', 'un',
'two', 'deux',
'three', 'trois');
London Perl Workshop
30th November 2013
31.
Fat Comma
●
●
The “fatcomma” is easier to understand
%german = (one
=> 'ein',
two
=> 'zwei',
three => 'drei');
London Perl Workshop
30th November 2013
32.
Accessing Hash Values
●
$three= $french{three};
●
print $german{two};
●
Note sigil change
●
For exactly the same reason
London Perl Workshop
30th November 2013
33.
Hash Slices
●
Just likearray slices
●
Returns a list of elements from a hash
●
●
print @french{'one','two','three'};
# prints "un", "deux" & "trois"
Strange sigil change
–
% becomes @
–
A list of values
London Perl Workshop
30th November 2013
34.
Setting Hash Values
●
$hash{foo}= 'something';
●
$hash{bar} = 'something else';
●
●
●
Also with slices
@hash{'foo', 'bar'} =
('something', 'else');
@hash{'foo', 'bar'} =
@hash{'bar', 'foo'};
London Perl Workshop
30th November 2013
35.
The Default Variable
●
●
●
●
ManyPerl operations either set $_ or use its value
if no other is given
print; # prints the value of $_
If a piece of Perl code seems to be missing a
variable, then it's probably using $_
Think of “it” or “that” in English
London Perl Workshop
30th November 2013
36.
Using the DefaultVariable
●
●
while (<$file>) {
if (/regex/) {
print;
}
}
Three uses of $_
–
Input
–
Match
–
Print
London Perl Workshop
30th November 2013
37.
Flow Control
●
Perl hasall the flow control features you'd expect
●
And some that you might not
●
Flow is controlled by Boolean logic
London Perl Workshop
30th November 2013
38.
Boolean Values inPerl
●
Perl has no Boolean data type
●
All scalar values are either true or false
●
Small set of false values
–
●
0, undef, empty string, empty list
Everything else is true
London Perl Workshop
30th November 2013
39.
Comparison Operators
●
Compare twovalues in some way
●
Are they equal
–
–
●
$x == $y or $x eq $y
$x != $y or $x ne $y
Is one greater than another
–
$x > $y or $x gt $y
–
$x >= $y or $x ge $y
London Perl Workshop
30th November 2013
40.
Two Sets ofOperators
●
Remember Perl converts between types
●
Is “0” the same as “0.0”?
–
–
As a number it is
As a string it isn't
●
Programmer needs to tell Perl the kind of comparison to make
●
String
–
●
eq, ne, lt, le, gt, ge
Number
–
==, !=, <, <=, >, >=
London Perl Workshop
30th November 2013
Boolean Operators
●
Combine conditionalexpressions
●
EXPR_1 and EXPR_2
true if both EXPR_1 and EXPR_2 are true
EXPR_1 or EXPR_2
–
●
–
true if either EXPR_1 or _EXPR_2 are true
●
Alternative syntax && for “and” and || for “or”
●
Different precedence though
London Perl Workshop
30th November 2013
43.
Short-Circuit Logic
●
●
●
●
●
EXPR_1 orEXPR_2
Only need to evaluate EXPR_2 if EXPR_1
evaluates as false
We can use this to make code easier to follow
open my $file, 'something.dat'
or die "Can't open file: $!";
@ARGV == 2 or print $usage_msg;
London Perl Workshop
30th November 2013
44.
Flow Control inPerl
●
Standard flow control statements
–
–
for
–
●
if/elsif/else
while
Some less standard ones
–
unless
–
foreach
–
until
London Perl Workshop
30th November 2013
45.
If / Else
●
●
if(EXPR) {
BLOCK
}
if (EXPR) {
BLOCK1
} else {
BLOCK2
}
London Perl Workshop
30th November 2013
46.
If / Else
●
●
if($lives < 0) {
die “Game over”;
}
if ($lives < 0) {
die “Game over”;
} else {
print “You won!”;
}
London Perl Workshop
30th November 2013
47.
If / Elsif/ Else
●
if (EXPR1) {
BLOCK1
} elsif (EXPR2) {
BLOCK2
} else {
BLOCK3
}
●
Note spelling of “elsif”
●
As many elsif clauses as you want
●
Else clause is optional
London Perl Workshop
30th November 2013
48.
If / Elsif/ Else
●
if ($temp > 25) {
print “Too hot”;
} elsif ($temp < 10) {
print “Too cold”;
} else {
print “Just right”;
}
London Perl Workshop
30th November 2013
49.
For
●
●
C-style for loop
for( INIT; EXPR; INCR ) {
BLOCK
}
–
–
If EXPR is false exit loop
–
Execute BLOCK and INCR
–
●
Execute INIT
Retry EXPR
Rarely used
London Perl Workshop
30th November 2013
50.
For
●
for ( $x= 0; $x <=10 ; ++$x ) {
print “$x squared is “, $x * $x;
}
London Perl Workshop
30th November 2013
While
●
while ($continue) {
if(do_something_useful()) {
print $interesting_value;
} else {
$continue = 0;
}
}
London Perl Workshop
30th November 2013
53.
Unless
●
●
●
●
●
Inverted if
unless (EXPR ) {
BLOCK
}
Exactly the same as
if ( ! EXPR ) {
BLOCK
}
Unless/else works
–
●
But is usually unhelpful
There is no elsunless
London Perl Workshop
30th November 2013
Foreach
●
●
Iterate over alist
foreach VAR ( LIST ) {
BLOCK
}
●
For each element in LIST
●
Put element in VAR
●
Execute BLOCK
●
Often simpler than equivalent for loop
London Perl Workshop
30th November 2013
56.
Foreach
●
foreach my $x( 1 .. 10 ) {
print “$x squared is “, $x * $x;
}
London Perl Workshop
30th November 2013
Until
●
until ($stop) {
if(do_something_useful()) {
print $interesting_value;
} else {
$stop = 1;
}
}
London Perl Workshop
30th November 2013
59.
Common Usage
●
●
A whileloop is often used to read from files
while (<$filehandle>) {
# Do stuff
}
●
Reads a record at a time
●
Stores the record in $_
London Perl Workshop
30th November 2013
60.
Statement Modifiers
●
Condition atend of statement
●
Invert logic
●
Can be more readable
–
–
print “Game over” unless $lives
–
●
help_text() if $option eq '-h'
print while <$filehandle>
Omit condition brackets
London Perl Workshop
30th November 2013
61.
Subroutines
●
Perl subroutines workmuch like other languages
●
Subroutines have a name and a block of code
●
Defined with the sub keyword
●
sub a_subroutine {
# do something useful
}
London Perl Workshop
30th November 2013
62.
Subroutine Arguments
●
●
Subroutine argumentsend up in @_
sub do_stuff {
my ($arg1, $arg2) = @_;
# Do something with
# $arg1 and $arg2
}
●
Variable number of arguments
London Perl Workshop
30th November 2013
63.
Pass By Reference
●
●
Valuesin @_ are aliases to external variables
my $x = 10;
square($x);
print $x; # prints 100
sub square {
$_[0] = $_[0] * $_[0];
}
●
Usually not a good idea
London Perl Workshop
30th November 2013
64.
Pass By Value
●
●
●
Takecopies of the arguments
Return changed values
my $x = 10;
my $sqr = square($x);
print $sqr; # prints 100
sub square {
my ($arg) = @_;
return $arg * $arg;
}
London Perl Workshop
30th November 2013
65.
Returning Values
●
●
●
Subroutines returna list
So it's simple to return a variable number of values
sub is_odd {
my @odds;
foreach (@_) {
push @odd, $_ if $_ % 2;
}
return @odds;
}
London Perl Workshop
30th November 2013
66.
Subroutine Variables
●
●
Variable canbe scoped to within a subroutine
sub with_var {
my $count = 0; # scoped to sub
print ++$count; # always prints 0
}
●
Good practice
●
Variables are recreated each time subroutine is called
London Perl Workshop
30th November 2013
67.
Static Variables
●
●
●
Use stateto declare variables that retain values
between calls
sub with_static_var {
state $count = 0; # scoped to
# sub
say ++$count; # increments on
# each call
}
Introduced in Perl 5.10.0
London Perl Workshop
30th November 2013
68.
Prototypes
●
●
You might seecode with prototypes for subroutines
sub with_a_prototype ($$$) {
my ($foo, $bar, $baz) = @_;
...
}
●
Not like prototypes in other languages
●
Rarely necessary
●
Often confusing
London Perl Workshop
30th November 2013
69.
References
●
Sometimes arrays andhashes are hard to use
●
Need a reference to a variable
●
A bit like a pointer
–
But cleverer
–
A reference knows what type it is a reference to
●
Unique identifier to a variable
●
Always a scalar value
London Perl Workshop
30th November 2013
70.
Creating a Reference
●
Use to get a reference to a variable
–
–
●
my $arr_ref = @array
my $hash_ref = %hash
Or create an anonymous variable directly
–
my $arr_ref = [ 'foo', 'bar', 'baz' ]
–
my $hash_ref = { one => 1, two => 2 }
London Perl Workshop
30th November 2013
71.
Using References
●
Use ->to access elements from a reference
–
–
●
$arr_ref->[0]
$hash_ref->{one}
Use @ or % to get whole variable
–
@array = @$arr_ref
–
%hash = %$hash_ref
London Perl Workshop
30th November 2013
72.
Why Use References
●
●
●
●
Arraysand hashes are hard to pass as parameters to
subroutines
my_sub(@arr1, @arr2)
And then inside subroutine
my (@a1, @a2) = @_
–
Doesn't work
–
Arrays are flattened in @_
–
List assignment works against us
London Perl Workshop
30th November 2013
73.
Parameters as References
●
●
●
●
Takereferences instead
my_sub(@arr1, @arr2)
And then inside subroutine
my ($a1, $a2) = @_
–
Works as expected
–
Array references are scalar values
–
List assignment is tamed
London Perl Workshop
30th November 2013
74.
More References
●
Printing areference is unhelpful
–
–
●
ARRAY(0xcce998)
HASH(0x2504998)
Use ref to see what type a reference is
–
ref [ 1, 2, 3 ]
●
–
ARRAY
ref { foo => 'bar' }
●
HASH
London Perl Workshop
30th November 2013
75.
Advanced References
●
Perl objectsare usually implemented as hash
references
–
●
You can create references to subroutines
–
●
But they are “blessed”
my $sub_ref = &my_sub;
$sub_ref->('some', 'parameters');
Anonymous subroutines
–
my $sub_ref = sub { print “Boo” };
$sub_ref->();
London Perl Workshop
30th November 2013
76.
Context
●
●
●
Perl expressions canevaluate to different values
according to context
The way that they are evaluated
@arr = localtime
–
●
(56, 31, 15, 22, 8, 112, 6, 265, 1)
$scalar = localtime
–
Sat Sep 22 15:31:56 2012
London Perl Workshop
30th November 2013
77.
Scalar Context
●
Assignment toa scalar variable
●
Boolean expression
–
if (@arr) { ... }
●
Some built-in functions that take one parameter
●
Operands to most operators
●
Force scalar context with scalar
–
print scalar localtime
London Perl Workshop
30th November 2013
78.
List Context
●
List assignments
–
–
($x,$y, $z) = some_function()
–
●
@arr = some_function()
($x) = some_function()
Most built-in functions
London Perl Workshop
30th November 2013
79.
Subroutine Parameters
●
●
●
●
A commonerror
sub something {
my $arg = @_;
...
}
Should be
sub something {
my ($arg) = @_;
...
}
London Perl Workshop
30th November 2013
80.
Context Rules
●
There areno general rules
●
Need to learn
●
Or read documentation
London Perl Workshop
30th November 2013
81.
Mind Your Contexts
●
Thedifference can be hard to spot
●
print “Time: ”, localtime;
●
print “Time: ” . localtime;
●
Comma imposes list context
●
Concatenation imposes scalar context
London Perl Workshop
30th November 2013
82.
File Input Contexts
●
Thefile input operator handles different contexts
●
$line = <$filehandle>;
●
@lines = <$filehandle>;
●
($line) = <$filehandle>; # danger!
London Perl Workshop
30th November 2013
CPAN
●
●
●
Comprehensive Perl ArchiveNetwork
Free Perl modules
Searchable
–
●
metacpan.org
Ecosystem of web sites
–
–
–
–
–
CPAN testers
cpanratings
Annocpan
CPAN deps
Many more...
London Perl Workshop
30th November 2013
85.
Installing CPAN Modules
●
Tryyour usual package repositories
–
–
apt-get
–
●
yum
ppm
May not have the modules you want
–
Or may have slightly older versions
London Perl Workshop
30th November 2013
86.
Installing CPAN Modules
●
Variouscommand line tools
–
–
CPANPLUS (cpanp)
–
●
CPAN Shell (cpan)
CPANMinus (cpanm)
Install dependencies too
London Perl Workshop
30th November 2013
Useful CPAN Libraries
●
PowerfulCPAN modules
●
Object-Oriented Programming
●
Database access
–
●
Object Relational Mapping
Web Development
–
MVC frameworks
–
Server/application glue
London Perl Workshop
30th November 2013
89.
Object Oriented Programming
●
Perlhas supported OOP since version 5.0
–
●
October 1994
Perl 5 OO sometimes described as appearing
“bolted on”
●
That's because it was bolted on
●
Powerful and flexible
●
Not particularly easy to understand
London Perl Workshop
30th November 2013
90.
Enter Moose
●
A completemodern object system for Perl 5
●
Based on experiments with Perl 6 object model
●
Built on top of Class::MOP
–
–
Set of abstractions for components of an object system
–
●
MOP - Meta Object Protocol
Classes, Objects, Methods, Attributes
An example might help
London Perl Workshop
30th November 2013
91.
Moose Example
●
package Point;
useMoose;
has 'x' => (isa
is
has 'y' => (isa
is
=>
=>
=>
=>
sub clear {
my $self = shift;
$self->x(0);
$self->y(0);
}
London Perl Workshop
30th November 2013
'Int',
'rw');
'Int',
'rw');
92.
Creating Attributes
●
has 'x'=> (isa => 'Int',
is => 'rw')
–
–
Constrained to be an integer
–
●
Creates an attribute called 'x'
Read-write
has 'y' => (isa => 'Int',
is => 'rw')
London Perl Workshop
30th November 2013
93.
Defining Methods
●
●
sub clear{
my $self = shift;
$self->x(0);
$self->y(0);
}
First parameter is the object
–
●
Stored as a blessed hash reference
Uses generated methods to set x & y
London Perl Workshop
30th November 2013
Extending Methods
●
after 'clear'=> sub {
my $self = shift;
$self->z(0);
};
●
New clear method for subclass
●
Called after method for superclass
London Perl Workshop
30th November 2013
97.
Using Moose Classes
●
●
●
Mooseclasses are used just like any other Perl class
$point = Point->new(x => 1,
y => 2);
say $point->x;
$p3d
= Point3D->new(x => 1,
y => 2,
z => 3);
$p3d->clear;
London Perl Workshop
30th November 2013
98.
More About Attributes
●
●
●
Usethe has keyword to define your class's
attributes
has 'first_name' =>
( is => 'rw' );
Use is to define rw or ro
London Perl Workshop
30th November 2013
99.
Getting & Setting
●
●
●
●
Bydefault each attribute creates a method of
the same name.
Used for both getting and setting the attribute
$dave->first_name('Dave');
say $dave->first_name;
London Perl Workshop
30th November 2013
100.
Required Attributes
●
By defaultMoose class attributes are optional
●
Change this with required
●
has 'name' => (
is
=> 'ro',
required => 1,
);
●
Forces constructor to expect a name
●
Although that name could be undef
London Perl Workshop
30th November 2013
101.
Attribute Defaults
●
●
●
●
Set adefault value for an attribute with default
has 'size' => (
is
=> 'rw',
default
=> 'medium',
);
Can use a subroutine reference
has 'size' => (
is
=> 'rw',
default
=> &rand_size,
);
London Perl Workshop
30th November 2013
More Moose
●
●
●
Many moreoptions
Support for concepts like delegation and roles
Powerful plugin support
–
●
MooseX::*
Lots of work going on in this area
London Perl Workshop
30th November 2013
104.
Database Access
●
Perl hasstandard tools for accessing databases
●
DBI (Database Interface)
–
●
Standardised interface
DBD (Database Driver)
–
Specific support for particular database engine
London Perl Workshop
30th November 2013
Object Relational Mapping
●
Databasesmap well to OO
●
Tables are classes
●
Rows are objects
●
Columns are attributes
●
Not a new idea
London Perl Workshop
30th November 2013
No More SQL
●
●
Oldstyle
my $sql = 'update thing
set foo = “new foo”
where id = 10';
my $sth = $dbh->prepare($sql);
$sth->execute;
London Perl Workshop
30th November 2013
109.
No More SQL
●
●
Newstyle
my $things =
$schema->resultset('Thing');
my $thing = $foo->find(10);
$thing->foo('new foo');
$thing->update;
London Perl Workshop
30th November 2013
110.
ORM Basics
●
Each classneeds some information
●
The table it represents
●
The columns in that table
●
The types of those columns
●
Which column is the primary key
●
Which columns are foreign keys
London Perl Workshop
30th November 2013
111.
Sample Artist Class
●
packageCD::Schema::Result::Artist;
use base qw/DBIx::Class::Core/;
__PACKAGE__->table('artist');
__PACKAGE__->add_columns(qw/ id name /);
__PACKAGE__->set_primary_key('id');
__PACKAGE__->has_many(cds =>
'CD::Schema::Result::CD', 'artist'
);
1;
London Perl Workshop
30th November 2013
112.
Sample Artist Class
●
packageCD::Schema::Result::Artist;
use base qw/DBIx::Class::Core/;
__PACKAGE__->table('artist');
__PACKAGE__->add_columns(qw/ id name /);
__PACKAGE__->set_primary_key('id');
__PACKAGE__->has_many(cds =>
'CD::Schema::Result::CD', 'artist'
);
1;
London Perl Workshop
30th November 2013
113.
Sample Artist Class
●
packageCD::Schema::Result::Artist;
use base qw/DBIx::Class::Core/;
__PACKAGE__->table('artist');
__PACKAGE__->add_columns(qw/ id name /);
__PACKAGE__->set_primary_key('id');
__PACKAGE__->has_many(cds =>
'CD::Schema::Result::CD', 'artist'
);
1;
London Perl Workshop
30th November 2013
114.
Sample Artist Class
●
packageCD::Schema::Result::Artist;
use base qw/DBIx::Class::Core/;
__PACKAGE__->table('artist');
__PACKAGE__->add_columns(qw/ id name /);
__PACKAGE__->set_primary_key('id');
__PACKAGE__->has_many(cds =>
'CD::Schema::Result::CD', 'artist'
);
1;
London Perl Workshop
30th November 2013
115.
Sample Artist Class
●
packageCD::Schema::Result::Artist;
use base qw/DBIx::Class::Core/;
__PACKAGE__->table('artist');
__PACKAGE__->add_columns(qw/ id name /);
__PACKAGE__->set_primary_key('id');
__PACKAGE__->has_many(cds =>
'CD::Schema::Result::CD', 'artist'
);
1;
London Perl Workshop
30th November 2013
116.
Sample CD Class
●
packageCD::Schema::Result::CD;
use base qw/DBIx::Class::Core/;
__PACKAGE__->table('cd');
__PACKAGE__->add_columns(qw/ id artist
title year /);
__PACKAGE__->set_primary_key('cd');
__PACKAGE__->belongs_to(artist =>
'CD::Schema::Result::Artist', 'artist'
);
1;
London Perl Workshop
30th November 2013
117.
Sample Schema Class
●
packageCD::Schema;
use base qw/DBIx::Class::Schema/;
__PACKAGE__->load_namespaces();
1;
London Perl Workshop
30th November 2013
118.
Listing Artists
●
use CD::Schema;
my$sch = CD::Schema->connect(
$dbi_dsn, $user, $pass
);
my $artists_rs =
$sch->resultset('Artist');
my @artists = $artists_rs->all;
London Perl Workshop
30th November 2013
119.
Listing Artists
●
foreach my$artist (@artists) {
say $artist->name;
foreach my $cd ($artist->cds) {
say “t”, $cd->title,
' (', $cd->year, ')';
}
}
London Perl Workshop
30th November 2013
120.
Searching Artists
●
●
my @davids= $artist_rs->search({
name => { like => 'David %' },
});
Powerful searching syntax
London Perl Workshop
30th November 2013
121.
Adding CD
●
my $bowie= $artist_rs->single({
name = 'David Bowie',
});
my $toy = $bowie->add_to_cds({
title => 'The Next Day',
year => 2013,
});
London Perl Workshop
30th November 2013
122.
Auto-Generating Schema
●
Writing schemaclasses is boring
●
Need to stay in step with database
●
Easy to make a mistake
●
Or to forget to update it
●
Auto-generate from database metadata
London Perl Workshop
30th November 2013
123.
ORM Basics
●
Each classneeds some information
●
The table it represents
●
The columns in that table
●
The types of those columns
●
Which column is the primary key
●
Which columns are foreign keys
●
Database knows all of these
London Perl Workshop
30th November 2013
Schema Loader Example
●
CREATEDATABASE CD;
CREATE TABLE artist (
id INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY,
name VARCHAR(200)
) ENGINE=InnoDB;
CREATE TABLE cd (
id INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY,
artist INTEGER,
title VARCHAR(200),
year INTEGER,
FOREIGN KEY (artist) REFERENCES artist (id)
) ENGINE=InnoDB;
London Perl Workshop
30th November 2013
126.
Schema Loader Example
●
●
●
$mysql -uuser -ppass -Dcd < cd.sql
$ dbicdump CD::Schema dbi:mysql:database=cd root ''
Dumping manual schema for CD::Schema to directory .
...
Schema dump completed.
$ find CD
CD
CD/Schema
CD/Schema/Result
CD/Schema/Result/Cd.pm
CD/Schema/Result/Artist.pm
CD/Schema.pm
London Perl Workshop
30th November 2013
127.
Web Development
●
Writing aweb application is always harder than
you think it will be
●
A good framework makes things easier
●
Takes care of the boring things
–
Authentication/Authorisation
–
Session management
–
Logging
–
Etc...
London Perl Workshop
30th November 2013
128.
Perl Web Frameworks
●
Plentyto choose from on CPAN
●
Web::Simple
–
●
Dancer
–
●
Lightweight and flexible
Mojolicious
–
●
Simple to install and use
“Next Generation Web Framework”
Catalyst
–
Extremely powerful
London Perl Workshop
30th November 2013
129.
Building on ExistingTools
●
Frameworks build on existing tools
●
Template Toolkit
–
Generating HTML
●
DBIx::Class
●
Moose
●
Not mandatory
–
Not opinionated software
London Perl Workshop
30th November 2013
PSGI & Plack
●
PSGIis the future of Perl web development
–
But it's here now
●
PSGI is a protocol specification
●
Plack is a toolkit
London Perl Workshop
30th November 2013
133.
What's the Problem?
●
Webapps run in many environments
●
CGI
●
mod_perl handler
●
FCGI
●
Etc...
●
All have different interfaces
London Perl Workshop
30th November 2013
134.
What's the Problem?
●
●
●
Thereare many Perl web frameworks
They all need to support all of the web
environments
Duplication of effort
–
Catalyst supports mod_perl
–
Dancer supports mod_perl
–
Web::Simple supports mod_perl
–
Etc...
London Perl Workshop
30th November 2013
135.
PSGI
●
●
Perl Server GatewayInterface
Defines interaction between web application and
web server
●
A bit like CGI
●
A lot like WSGI
London Perl Workshop
30th November 2013
136.
What's the Advantage?
●
Webframeworks only support PSGI interface
●
One PSGI interface per web environment
●
Less duplication of effort
●
Bonus
●
Easily portable code
London Perl Workshop
30th November 2013
PSGI Definition
●
A PSGIapplication is
●
A reference to a subroutine
●
Input is a hash
–
●
Actually a hash reference
Output is a three-element array
–
HTTP status code
–
Headers
–
Body
London Perl Workshop
30th November 2013
139.
Reference to Subroutine
●
my$app = sub {
my $env = shift;
return [
200,
[ ‘Content-Type’,‘text/plain’ ],
[ ‘Hello World’ ],
];
};
London Perl Workshop
30th November 2013
140.
Reference to Subroutine
●
my$app = sub {
my $env = shift;
return [
200,
[ ‘Content-Type’,‘text/plain’ ],
[ ‘Hello World’ ],
];
};
London Perl Workshop
30th November 2013
141.
Hash Reference
●
my $app= sub {
my $env = shift;
return [
200,
[ ‘Content-Type’,‘text/plain’ ],
[ ‘Hello World’ ],
];
};
London Perl Workshop
30th November 2013
142.
Hash Reference
●
my $app= sub {
my $env = shift;
return [
200,
[ ‘Content-Type’,‘text/plain’ ],
[ ‘Hello World’ ],
];
};
London Perl Workshop
30th November 2013
143.
Return Array Reference
●
my$app = sub {
my $env = shift;
return [
200,
[ ‘Content-Type’,‘text/plain’ ],
[ ‘Hello World’ ],
];
};
London Perl Workshop
30th November 2013
144.
Return Array Reference
●
my$app = sub {
my $env = shift;
return [
200,
[ ‘Content-Type’,‘text/plain’ ],
[ ‘Hello World’ ],
];
};
London Perl Workshop
30th November 2013
145.
Plack
●
●
PSGI is justa specification
Plack is a bundle of tools for working with that
specification
–
–
●
Available from CPAN
A lot like Rack
Many useful modules and programs
London Perl Workshop
30th November 2013
146.
plackup
●
●
Test PSGI server
$plackup app.psgi
HTTP::Server::PSGI: Accepting connections at
http://localhost:5000/
London Perl Workshop
30th November 2013
147.
Middleware
●
Middleware wraps aroundan application
●
Returns another PSGI application
●
Simple spec makes this easy
●
Plack::Middleware::*
●
Plack::Builder adds middleware configuration
language
London Perl Workshop
30th November 2013
148.
Middleware Example
●
use Plack::Builder;
usePlack::Middleware::Runtime;
my $app = sub {
my $env = shift;
return [
200,
[ 'Content-type', 'text/plain' ],
[ 'Hello world' ],
]
};
builder {
enable 'Runtime';
$app;
}
London Perl Workshop
30th November 2013
149.
Middleware Example
●
$ HEADhttp://localhost:5000
200 OK
Date: Tue, 20 Jul 2010 20:25:52 GMT
Server: HTTP::Server::PSGI
Content-Length: 11
Content-Type: text/plain
Client-Date: Tue, 20 Jul 2010 20:25:52 GMT
Client-Peer: 127.0.0.1:5000
Client-Response-Num: 1
X-Runtime: 0.000050
London Perl Workshop
30th November 2013
150.
Plack::App::*
●
Ready-made solutions forcommon situations
●
Plack::App::CGIBin
–
●
Plack::App::Directory
–
●
cgi-bin replacement
Serve files with directory index
Plack::App::URLMap
–
Map apps to different paths
London Perl Workshop
30th November 2013
151.
Application Example
●
use Plack::App::CGIBin;
usePlack::Builder;
my $app = Plack::App::CGIBin->new(
root => '/var/www/cgi-bin'
)->to_app;
builder {
mount '/cgi-bin' => $app;
};
London Perl Workshop
30th November 2013
152.
Framework Support
●
●
●
Most modernPerl frameworks already support
PSGI
Catalyst, CGI::Application, Dancer, Jifty, Mason,
Maypole, Mojolicious, Squatting, Web::Simple
Many more
London Perl Workshop
30th November 2013
153.
PSGI Server Support
●
nginxsupport
●
mod_psgi
●
Plack::Handler::Apache2
London Perl Workshop
30th November 2013
154.
PSGI Server Support
●
●
●
Manynew web servers support PSGI
Starman, Starlet, Twiggy, Corona,
HTTP::Server::Simple::PSGI
Perlbal::Plugin::PSGI
London Perl Workshop
30th November 2013
155.
PSGI/Plack Summary
●
PSGI isa specification
●
Plack is an implementation
●
PSGI makes your life easier
●
●
Most of the frameworks and servers you use
already support PSGI
No excuse not to use it
London Perl Workshop
30th November 2013
Further Information
●
Very high-leveloverview
●
Lots of information available
–
Perl documentation
–
Books
–
Web sites
–
Mailing lists
–
User groups
–
Conferences
London Perl Workshop
30th November 2013
158.
Perl Documentation
●
Perl comeswith a huge documentation set
●
Access it via “perldoc”
●
perldoc perl
●
perldoc perltoc
●
perldoc perlfaq
●
perldoc perldoc
London Perl Workshop
30th November 2013
159.
Perldoc Options
●
Documentation fora particular function
–
●
Documentation for a particular variable
–
●
perldoc -f print
perldoc -v @_
Search the FAQ for a keyword
–
perldoc -q sort
London Perl Workshop
30th November 2013
160.
Perl Books
●
Essential Perlbooks
●
Learning Perl (6ed)
–
●
Programming Perl (4ed)
–
●
Schwartz, Phoenix and foy
Wall, Christiansen, Orwant and foy
Perl Best Practices
–
Damian Conway
London Perl Workshop
30th November 2013
161.
Perl Books
●
Effective PerlProgramming
–
●
Intermediate Perl (2ed)
–
●
Hall, McAdams and foy
Schwartz, foy and Phoenix
Mastering Perl
–
brian d foy
London Perl Workshop
30th November 2013
Perl Web Sites
●
Perlhome page
–
●
Perl documentation
–
●
www.perl.org
perldoc.perl.org
CPAN
–
metacpan.org
London Perl Workshop
30th November 2013
165.
Perl Web Sites
●
PerlNews
–
●
perlnews.org
Perl Blogs
–
–
●
blogs.perl.org
ironman.enlightenedperl.org
Perl Foundation
–
perlfoundation.org
London Perl Workshop
30th November 2013
166.
Perl Web Sites
●
PerlUser Groups (Perl Mongers)
–
●
www.pm.org
Perl Help
–
–
●
perlmonks.org
stackoverflow.com/questions/tagged/perl
Perl Tutorials
–
perl-tutorial.org
London Perl Workshop
30th November 2013
167.
Perl Mailing Lists
●
Dozensof lists
–
●
lists.perl.org
Perl Weekly
–
perlweekly.com
London Perl Workshop
30th November 2013
168.
Perl User Groups
●
Perluser groups are called “Perl Mongers”
●
Hundreds of groups worldwide
–
●
www.pm.org
London.pm one of the largest groups
–
london.pm.org
●
Monthly social meetings
●
Bi-monthly (ish) technical meetings
●
Mailing list
London Perl Workshop
30th November 2013
169.
Perl Conferences
●
OSCON (OpenSource Convention)
–
–
●
Originally The Perl Conference
20 – 24 July 2014, Portland OR
YAPC (Yet Another Perl Conference)
–
23 – 25 June 2014, Orlando FL
–
August 2014, Sofia, Bulgaria
London Perl Workshop
30th November 2013
170.
Perl Workshops
●
Low cost(free)
●
One-day
●
Many cities all over the world
●
London Perl Workshop
–
londonperlworkshop.org.uk
–
Nov/Dec
London Perl Workshop
30th November 2013
171.
The End
●
Thank youfor coming
●
Hope you enjoyed it
●
Hope it was useful
●
Any questions?
London Perl Workshop
30th November 2013