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.
5. What is Modern Perl
●
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 release cycle
–
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 is maintained 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
10. Introduction to Perl
●
Quick look at some Perl features
●
Differences from other languages
●
Variables
●
Flow control
●
Subroutines
●
Context
London Perl Workshop
30th November 2013
11. Variables in Perl
●
Perl variables 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
●
Not the 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 alphanumeric characters 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 indicate variable type
●
Scalars use $
–
●
Arrays use @
–
●
$doctor
@time_lords
Hashes use %
–
%companions
London Perl Workshop
30th November 2013
15. Declaring variables
●
You don't need 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 a single 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 converts between 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 quotes don'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 backslash to 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 is a 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
●
Choose characters 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 scalar that 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 contain an 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 individual elements 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 sigil changes 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 a list 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 is the 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
●
Arrays and 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 “fat comma” 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 like array 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
●
●
●
●
Many Perl 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 Default Variable
●
●
while (<$file>) {
if (/regex/) {
print;
}
}
Three uses of $_
–
Input
–
Match
–
Print
London Perl Workshop
30th November 2013
37. Flow Control
●
Perl has all 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 in Perl
●
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 two values 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 of Operators
●
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
42. Boolean Operators
●
Combine conditional expressions
●
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 or EXPR_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 in Perl
●
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
52. 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
55. Foreach
●
●
Iterate over a list
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
58. Until
●
until ($stop) {
if (do_something_useful()) {
print $interesting_value;
} else {
$stop = 1;
}
}
London Perl Workshop
30th November 2013
59. Common Usage
●
●
A while loop 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 at end 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 work much 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 arguments end 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
●
●
Values in @_ 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
●
●
●
Take copies 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 return a 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 can be 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 state to 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 see code 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 and hashes 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
●
●
●
●
Arrays and 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
●
●
●
●
Take references 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 a reference 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 objects are 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 can evaluate 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 to a 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 common error
sub something {
my $arg = @_;
...
}
Should be
sub something {
my ($arg) = @_;
...
}
London Perl Workshop
30th November 2013
80. Context Rules
●
There are no general rules
●
Need to learn
●
Or read documentation
London Perl Workshop
30th November 2013
81. Mind Your Contexts
●
The difference 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
●
The file input operator handles different contexts
●
$line = <$filehandle>;
●
@lines = <$filehandle>;
●
($line) = <$filehandle>; # danger!
London Perl Workshop
30th November 2013
84. CPAN
●
●
●
Comprehensive Perl Archive Network
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
●
Try your 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
●
Various command line tools
–
–
CPANPLUS (cpanp)
–
●
CPAN Shell (cpan)
CPANMinus (cpanm)
Install dependencies too
London Perl Workshop
30th November 2013
88. Useful CPAN Libraries
●
Powerful CPAN 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
●
Perl has 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 complete modern 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;
use Moose;
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
96. 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
●
●
●
Moose classes 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
●
●
●
Use the 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
●
●
●
●
By default 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 default Moose 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 a default 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
103. More Moose
●
●
●
Many more options
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 has standard tools for accessing databases
●
DBI (Database Interface)
–
●
Standardised interface
DBD (Database Driver)
–
Specific support for particular database engine
London Perl Workshop
30th November 2013
106. Object Relational Mapping
●
Databases map well to OO
●
Tables are classes
●
Rows are objects
●
Columns are attributes
●
Not a new idea
London Perl Workshop
30th November 2013
108. No More SQL
●
●
Old style
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
●
●
New style
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 class needs 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
●
package CD::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
●
package CD::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
●
package CD::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
●
package CD::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
●
package CD::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
●
package CD::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
●
package CD::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 schema classes 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 class needs 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
125. Schema Loader Example
●
CREATE DATABASE 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 a web 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
●
Plenty to 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 Existing Tools
●
Frameworks build on existing tools
●
Template Toolkit
–
Generating HTML
●
DBIx::Class
●
Moose
●
Not mandatory
–
Not opinionated software
London Perl Workshop
30th November 2013
132. PSGI & Plack
●
PSGI is 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?
●
Web apps 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?
●
●
●
There are 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 Gateway Interface
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?
●
Web frameworks only support PSGI interface
●
One PSGI interface per web environment
●
Less duplication of effort
●
Bonus
●
Easily portable code
London Perl Workshop
30th November 2013
138. PSGI Definition
●
A PSGI application 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 just a 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 around an 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;
use Plack::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
●
$ HEAD http://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 for common 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;
use Plack::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 modern Perl 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
●
nginx support
●
mod_psgi
●
Plack::Handler::Apache2
London Perl Workshop
30th November 2013
154. PSGI Server Support
●
●
●
Many new 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 is a 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
157. Further Information
●
Very high-level overview
●
Lots of information available
–
Perl documentation
–
Books
–
Web sites
–
Mailing lists
–
User groups
–
Conferences
London Perl Workshop
30th November 2013
158. Perl Documentation
●
Perl comes with 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 for a 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 Perl books
●
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 Perl Programming
–
●
Intermediate Perl (2ed)
–
●
Hall, McAdams and foy
Schwartz, foy and Phoenix
Mastering Perl
–
brian d foy
London Perl Workshop
30th November 2013
164. Perl Web Sites
●
Perl home page
–
●
Perl documentation
–
●
www.perl.org
perldoc.perl.org
CPAN
–
metacpan.org
London Perl Workshop
30th November 2013
165. Perl Web Sites
●
Perl News
–
●
perlnews.org
Perl Blogs
–
–
●
blogs.perl.org
ironman.enlightenedperl.org
Perl Foundation
–
perlfoundation.org
London Perl Workshop
30th November 2013
166. Perl Web Sites
●
Perl User 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
●
Dozens of lists
–
●
lists.perl.org
Perl Weekly
–
perlweekly.com
London Perl Workshop
30th November 2013
168. Perl User Groups
●
Perl user 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 (Open Source 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 you for coming
●
Hope you enjoyed it
●
Hope it was useful
●
Any questions?
London Perl Workshop
30th November 2013