SlideShare une entreprise Scribd logo
1  sur  172
Télécharger pour lire hors ligne
Modern Perl for
Non-Perl
Programmers
Dave Cross
dave@mag-sol.com
Topics
●

What is Modern Perl?

●

Variables

●

Flow control

●

Subroutines

●

References

●

Context

London Perl Workshop
30th November 2013
Topics
●

CPAN

●

Useful Libraries
–
–

Database Access

–
●

Object Oriented Programming
Web Programming

Further Information

London Perl Workshop
30th November 2013
What is
Modern Perl?
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
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
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
Current Version
●

5.18.1
–

●

12 Aug 2013

5.20.0 due next spring
–

5.19.6

–

20 Nov 2013

London Perl Workshop
30th November 2013
Introduction
to Perl
Introduction to Perl
●

Quick look at some Perl features

●

Differences from other languages

●

Variables

●

Flow control

●

Subroutines

●

Context

London Perl Workshop
30th November 2013
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
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
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
Sigils
●

Punctuations marks indicate variable type

●

Scalars use $
–

●

Arrays use @
–

●

$doctor
@time_lords

Hashes use %
–

%companions

London Perl Workshop
30th November 2013
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Fat Comma
●
●

The “fat comma” is easier to understand
%german = (one
=> 'ein',
two
=> 'zwei',
three => 'drei');

London Perl Workshop
30th November 2013
Accessing Hash Values
●

$three = $french{three};

●

print $german{two};

●

Note sigil change

●

For exactly the same reason

London Perl Workshop
30th November 2013
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
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
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
Using the Default Variable
●

●

while (<$file>) {
if (/regex/) {
print;
}
}
Three uses of $_
–

Input

–

Match

–

Print

London Perl Workshop
30th November 2013
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
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
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
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
Comparison Examples
●

62 > 42

# true

●

'0' == (3 * 2) - 6

# true

●

'apple' gt 'banana' # false

●

'apple' == 'banana' # true(!)

●

1 + 2 == '3 bears'

# true

●

1 + 2 == 'three'

# false

London Perl Workshop
30th November 2013
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
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
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
If / Else
●

●

if (EXPR) {
BLOCK
}
if (EXPR) {
BLOCK1
} else {
BLOCK2
}

London Perl Workshop
30th November 2013
If / Else
●

●

if ($lives < 0) {
die “Game over”;
}
if ($lives < 0) {
die “Game over”;
} else {
print “You won!”;
}

London Perl Workshop
30th November 2013
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
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
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
For
●

for ( $x = 0; $x <=10 ; ++$x ) {
print “$x squared is “, $x * $x;
}

London Perl Workshop
30th November 2013
While
●
●

Execute loop while a condition is true
while (EXPR) {
BLOCK
}

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
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
Unless
●

unless ($lives) {
die “Game over”;
}

London Perl Workshop
30th November 2013
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
Foreach
●

foreach my $x ( 1 .. 10 ) {
print “$x squared is “, $x * $x;
}

London Perl Workshop
30th November 2013
Until
●
●

●
●

Inverted while
until ( EXPR ) {
BLOCK
}
Exactly the same as
while ( ! EXPR ) {
BLOCK
}

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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Subroutine Parameters
●
●

●

●

A common error
sub something {
my $arg = @_;
...
}
Should be
sub something {
my ($arg) = @_;
...
}

London Perl Workshop
30th November 2013
Context Rules
●

There are no general rules

●

Need to learn

●

Or read documentation

London Perl Workshop
30th November 2013
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
File Input Contexts
●

The file input operator handles different contexts

●

$line = <$filehandle>;

●

@lines = <$filehandle>;

●

($line) = <$filehandle>; # danger!

London Perl Workshop
30th November 2013
CPAN
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
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
Installing CPAN Modules
●

Various command line tools
–
–

CPANPLUS (cpanp)

–
●

CPAN Shell (cpan)
CPANMinus (cpanm)

Install dependencies too

London Perl Workshop
30th November 2013
Useful CPAN
Libraries
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
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
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
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');
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
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
Subclassing
●

package Point3D;
use Moose;
extends 'Point';
has 'z' => (isa => 'Int', is => 'rw');
after 'clear' => sub {
my $self = shift;
$self->z(0);
};

London Perl Workshop
30th November 2013
Subclassing
●

extends 'Point'
–

●

Define which class we're a subclass of

has 'z' => (
isa = 'Int', is => 'rw'
)
–

Adds new attribute 'z'

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
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
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
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
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
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
More Attribute Properties
●

lazy
–

●

trigger
–

●

Subroutine called after the attribute is set

isa
–

●

Only populate attribute when queried

Set the type of an attribute

Many more

London Perl Workshop
30th November 2013
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
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
Good and Bad
●

Good
–
–

●

Standardised
Supports many databases

Bad
–

SQL

London Perl Workshop
30th November 2013
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
DBIx::Class
●

DBI extension

●

Define classes in Perl

●

We write Perl

●

DBIx::Class writes the SQL

London Perl Workshop
30th November 2013
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
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
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
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
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
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
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
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
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
Sample Schema Class
●

package CD::Schema;
use base qw/DBIx::Class::Schema/;
__PACKAGE__->load_namespaces();
1;

London Perl Workshop
30th November 2013
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
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
Searching Artists
●

●

my @davids = $artist_rs->search({
name => { like => 'David %' },
});
Powerful searching syntax

London Perl Workshop
30th November 2013
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
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
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
DBIx::Class::Schema::Loader
●

Connects to database

●

Queries metadata

●

Generates class definitions

●

Writes them to disk

●

Command line program
–

dbicdump

London Perl Workshop
30th November 2013
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
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
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
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
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
Dancer
●

●

Route-based framework
use Dancer;
get '/' => sub {
return 'Hello World”;
};
dance;

●

bin/app.pl

London Perl Workshop
30th November 2013
Catalyst
●

MVC framework
–

Model, View, Controller

●

Most popular Perl web framework

●

Powerful

●

Flexible

London Perl Workshop
30th November 2013
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
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
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
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
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
Other Advantages
●

Standardised development servers

●

Easier testing

●

Middleware

London Perl Workshop
30th November 2013
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
Reference to Subroutine
●

my $app = sub {
my $env = shift;
return [
200,
[ ‘Content-Type’,‘text/plain’ ],
[ ‘Hello World’ ],
];
};

London Perl Workshop
30th November 2013
Reference to Subroutine
●

my $app = sub {
my $env = shift;
return [
200,
[ ‘Content-Type’,‘text/plain’ ],
[ ‘Hello World’ ],
];
};

London Perl Workshop
30th November 2013
Hash Reference
●

my $app = sub {
my $env = shift;
return [
200,
[ ‘Content-Type’,‘text/plain’ ],
[ ‘Hello World’ ],
];
};

London Perl Workshop
30th November 2013
Hash Reference
●

my $app = sub {
my $env = shift;
return [
200,
[ ‘Content-Type’,‘text/plain’ ],
[ ‘Hello World’ ],
];
};

London Perl Workshop
30th November 2013
Return Array Reference
●

my $app = sub {
my $env = shift;
return [
200,
[ ‘Content-Type’,‘text/plain’ ],
[ ‘Hello World’ ],
];
};

London Perl Workshop
30th November 2013
Return Array Reference
●

my $app = sub {
my $env = shift;
return [
200,
[ ‘Content-Type’,‘text/plain’ ],
[ ‘Hello World’ ],
];
};

London Perl Workshop
30th November 2013
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
plackup
●
●

Test PSGI server
$ plackup app.psgi
HTTP::Server::PSGI: Accepting connections at
http://localhost:5000/

London Perl Workshop
30th November 2013
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
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
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
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
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
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
PSGI Server Support
●

nginx support

●

mod_psgi

●

Plack::Handler::Apache2

London Perl Workshop
30th November 2013
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
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
Further
Information
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
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
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
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
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
Perl Books
●

Beginning Perl
–

●

Curtis Poe

Perl Testing – A Developers Notebook
–

Langworth, chromatic

London Perl Workshop
30th November 2013
Perl Books
●

Modern Perl
–

●

chromatic

Definitive Guide to Catalyst
–

Diment, Trout

London Perl Workshop
30th November 2013
Perl Web Sites
●

Perl home page
–

●

Perl documentation
–

●

www.perl.org
perldoc.perl.org

CPAN
–

metacpan.org

London Perl Workshop
30th November 2013
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
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
Perl Mailing Lists
●

Dozens of lists
–

●

lists.perl.org

Perl Weekly
–

perlweekly.com

London Perl Workshop
30th November 2013
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
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
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
The End
●

Thank you for coming

●

Hope you enjoyed it

●

Hope it was useful

●

Any questions?

London Perl Workshop
30th November 2013
London Perl Workshop
30th November 2013

Contenu connexe

Tendances

Php Chapter 2 3 Training
Php Chapter 2 3 TrainingPhp Chapter 2 3 Training
Php Chapter 2 3 TrainingChris Chubb
 
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur..."How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...Fwdays
 
Practical approach to perl day1
Practical approach to perl day1Practical approach to perl day1
Practical approach to perl day1Rakesh Mukundan
 
Lecture 22
Lecture 22Lecture 22
Lecture 22rhshriva
 
perl course-in-mumbai
 perl course-in-mumbai perl course-in-mumbai
perl course-in-mumbaivibrantuser
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Nikita Popov
 
PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021Ayesh Karunaratne
 
Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Bozhidar Boshnakov
 
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...Andrea Telatin
 
PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2Kumar
 
Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
Anonymous Functions in PHP 5.3 - Matthew Weier O’PhinneyAnonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
Anonymous Functions in PHP 5.3 - Matthew Weier O’PhinneyHipot Studio
 
Arrays &amp; functions in php
Arrays &amp; functions in phpArrays &amp; functions in php
Arrays &amp; functions in phpAshish Chamoli
 
What You Need to Know about Lambdas
What You Need to Know about LambdasWhat You Need to Know about Lambdas
What You Need to Know about LambdasRyan Knight
 
PHP 8.1 - What's new and changed
PHP 8.1 - What's new and changedPHP 8.1 - What's new and changed
PHP 8.1 - What's new and changedAyesh Karunaratne
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
Yapc::NA::2009 - Command Line Perl
Yapc::NA::2009 - Command Line PerlYapc::NA::2009 - Command Line Perl
Yapc::NA::2009 - Command Line PerlBruce Gray
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and ArraysWebStackAcademy
 

Tendances (20)

Perl tutorial
Perl tutorialPerl tutorial
Perl tutorial
 
Php Chapter 2 3 Training
Php Chapter 2 3 TrainingPhp Chapter 2 3 Training
Php Chapter 2 3 Training
 
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur..."How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
 
Practical approach to perl day1
Practical approach to perl day1Practical approach to perl day1
Practical approach to perl day1
 
Lecture 22
Lecture 22Lecture 22
Lecture 22
 
perl course-in-mumbai
 perl course-in-mumbai perl course-in-mumbai
perl course-in-mumbai
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?
 
PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021
 
Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)
 
Cs3430 lecture 15
Cs3430 lecture 15Cs3430 lecture 15
Cs3430 lecture 15
 
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
 
PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2
 
Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
Anonymous Functions in PHP 5.3 - Matthew Weier O’PhinneyAnonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
 
Arrays &amp; functions in php
Arrays &amp; functions in phpArrays &amp; functions in php
Arrays &amp; functions in php
 
What You Need to Know about Lambdas
What You Need to Know about LambdasWhat You Need to Know about Lambdas
What You Need to Know about Lambdas
 
PHP 8.1 - What's new and changed
PHP 8.1 - What's new and changedPHP 8.1 - What's new and changed
PHP 8.1 - What's new and changed
 
Perl
PerlPerl
Perl
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Yapc::NA::2009 - Command Line Perl
Yapc::NA::2009 - Command Line PerlYapc::NA::2009 - Command Line Perl
Yapc::NA::2009 - Command Line Perl
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
 

En vedette

The MetaCPAN VM for Dummies Part One (Installation)
The MetaCPAN VM for Dummies Part One (Installation)The MetaCPAN VM for Dummies Part One (Installation)
The MetaCPAN VM for Dummies Part One (Installation)Olaf Alders
 
The MetaCPAN VM Part II (Using the VM)
The MetaCPAN VM Part II (Using the VM)The MetaCPAN VM Part II (Using the VM)
The MetaCPAN VM Part II (Using the VM)Olaf Alders
 
Ab(Using) the MetaCPAN API for Fun and Profit v2013
Ab(Using) the MetaCPAN API for Fun and Profit v2013Ab(Using) the MetaCPAN API for Fun and Profit v2013
Ab(Using) the MetaCPAN API for Fun and Profit v2013Olaf Alders
 
TEDx Manchester: AI & The Future of Work
TEDx Manchester: AI & The Future of WorkTEDx Manchester: AI & The Future of Work
TEDx Manchester: AI & The Future of WorkVolker Hirsch
 

En vedette (6)

The MetaCPAN VM for Dummies Part One (Installation)
The MetaCPAN VM for Dummies Part One (Installation)The MetaCPAN VM for Dummies Part One (Installation)
The MetaCPAN VM for Dummies Part One (Installation)
 
The MetaCPAN VM Part II (Using the VM)
The MetaCPAN VM Part II (Using the VM)The MetaCPAN VM Part II (Using the VM)
The MetaCPAN VM Part II (Using the VM)
 
Ab(Using) the MetaCPAN API for Fun and Profit v2013
Ab(Using) the MetaCPAN API for Fun and Profit v2013Ab(Using) the MetaCPAN API for Fun and Profit v2013
Ab(Using) the MetaCPAN API for Fun and Profit v2013
 
Medium Perl
Medium PerlMedium Perl
Medium Perl
 
TEDx Manchester: AI & The Future of Work
TEDx Manchester: AI & The Future of WorkTEDx Manchester: AI & The Future of Work
TEDx Manchester: AI & The Future of Work
 
Build Features, Not Apps
Build Features, Not AppsBuild Features, Not Apps
Build Features, Not Apps
 

Similaire à Modern Perl for Non-Perl Programmers

Our Friends the Utils: A highway traveled by wheels we didn't re-invent.
Our Friends the Utils: A highway traveled by wheels we didn't re-invent. Our Friends the Utils: A highway traveled by wheels we didn't re-invent.
Our Friends the Utils: A highway traveled by wheels we didn't re-invent. Workhorse Computing
 
Python bible
Python biblePython bible
Python bibleadarsh j
 
Engineering Student MuleSoft Meetup#6 - Basic Understanding of DataWeave With...
Engineering Student MuleSoft Meetup#6 - Basic Understanding of DataWeave With...Engineering Student MuleSoft Meetup#6 - Basic Understanding of DataWeave With...
Engineering Student MuleSoft Meetup#6 - Basic Understanding of DataWeave With...Jitendra Bafna
 
Ruby Basics by Rafiq
Ruby Basics by RafiqRuby Basics by Rafiq
Ruby Basics by RafiqRafiqdeen
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonAhmed Salama
 
Perl 6 command line scripting
Perl 6 command line scriptingPerl 6 command line scripting
Perl 6 command line scriptingSimon Proctor
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To ScalaBasuk
 
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1Mukesh Kumar
 
Open Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul
 
BITS: Introduction to relational databases and MySQL - Schema design
BITS: Introduction to relational databases and MySQL - Schema designBITS: Introduction to relational databases and MySQL - Schema design
BITS: Introduction to relational databases and MySQL - Schema designBITS
 
Perl - laziness, impatience, hubris, and one liners
Perl - laziness, impatience, hubris, and one linersPerl - laziness, impatience, hubris, and one liners
Perl - laziness, impatience, hubris, and one linersKirk Kimmel
 
Viliam Ganz - Domain Specific Languages
Viliam Ganz - Domain Specific LanguagesViliam Ganz - Domain Specific Languages
Viliam Ganz - Domain Specific LanguagesDavinci software
 

Similaire à Modern Perl for Non-Perl Programmers (20)

Our Friends the Utils: A highway traveled by wheels we didn't re-invent.
Our Friends the Utils: A highway traveled by wheels we didn't re-invent. Our Friends the Utils: A highway traveled by wheels we didn't re-invent.
Our Friends the Utils: A highway traveled by wheels we didn't re-invent.
 
Cs3430 lecture 16
Cs3430 lecture 16Cs3430 lecture 16
Cs3430 lecture 16
 
Dart workshop
Dart workshopDart workshop
Dart workshop
 
Software Developer Training
Software Developer TrainingSoftware Developer Training
Software Developer Training
 
Python bible
Python biblePython bible
Python bible
 
Engineering Student MuleSoft Meetup#6 - Basic Understanding of DataWeave With...
Engineering Student MuleSoft Meetup#6 - Basic Understanding of DataWeave With...Engineering Student MuleSoft Meetup#6 - Basic Understanding of DataWeave With...
Engineering Student MuleSoft Meetup#6 - Basic Understanding of DataWeave With...
 
Ruby Basics by Rafiq
Ruby Basics by RafiqRuby Basics by Rafiq
Ruby Basics by Rafiq
 
Ruby training day1
Ruby training day1Ruby training day1
Ruby training day1
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Perl 6 command line scripting
Perl 6 command line scriptingPerl 6 command line scripting
Perl 6 command line scripting
 
Neo4j: Graph-like power
Neo4j: Graph-like powerNeo4j: Graph-like power
Neo4j: Graph-like power
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
 
7.1.intro perl
7.1.intro perl7.1.intro perl
7.1.intro perl
 
Perl5 Memory Manglement
Perl5 Memory ManglementPerl5 Memory Manglement
Perl5 Memory Manglement
 
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
 
Open Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul Language PL/SQL
Open Gurukul Language PL/SQL
 
BITS: Introduction to relational databases and MySQL - Schema design
BITS: Introduction to relational databases and MySQL - Schema designBITS: Introduction to relational databases and MySQL - Schema design
BITS: Introduction to relational databases and MySQL - Schema design
 
Perl - laziness, impatience, hubris, and one liners
Perl - laziness, impatience, hubris, and one linersPerl - laziness, impatience, hubris, and one liners
Perl - laziness, impatience, hubris, and one liners
 
Viliam Ganz - Domain Specific Languages
Viliam Ganz - Domain Specific LanguagesViliam Ganz - Domain Specific Languages
Viliam Ganz - Domain Specific Languages
 
Object Oriented Javascript
Object Oriented JavascriptObject Oriented Javascript
Object Oriented Javascript
 

Plus de Dave Cross

Measuring the Quality of Your Perl Code
Measuring the Quality of Your Perl CodeMeasuring the Quality of Your Perl Code
Measuring the Quality of Your Perl CodeDave Cross
 
Apollo 11 at 50 - A Simple Twitter Bot
Apollo 11 at 50 - A Simple Twitter BotApollo 11 at 50 - A Simple Twitter Bot
Apollo 11 at 50 - A Simple Twitter BotDave Cross
 
Monoliths, Balls of Mud and Silver Bullets
Monoliths, Balls of Mud and Silver BulletsMonoliths, Balls of Mud and Silver Bullets
Monoliths, Balls of Mud and Silver BulletsDave Cross
 
The Professional Programmer
The Professional ProgrammerThe Professional Programmer
The Professional ProgrammerDave Cross
 
I'm A Republic (Honest!)
I'm A Republic (Honest!)I'm A Republic (Honest!)
I'm A Republic (Honest!)Dave Cross
 
Web Site Tune-Up - Improve Your Googlejuice
Web Site Tune-Up - Improve Your GooglejuiceWeb Site Tune-Up - Improve Your Googlejuice
Web Site Tune-Up - Improve Your GooglejuiceDave Cross
 
Modern Perl Web Development with Dancer
Modern Perl Web Development with DancerModern Perl Web Development with Dancer
Modern Perl Web Development with DancerDave Cross
 
Freeing Tower Bridge
Freeing Tower BridgeFreeing Tower Bridge
Freeing Tower BridgeDave Cross
 
Error(s) Free Programming
Error(s) Free ProgrammingError(s) Free Programming
Error(s) Free ProgrammingDave Cross
 
Modern Web Development with Perl
Modern Web Development with PerlModern Web Development with Perl
Modern Web Development with PerlDave Cross
 
Improving Dev Assistant
Improving Dev AssistantImproving Dev Assistant
Improving Dev AssistantDave Cross
 
Conference Driven Publishing
Conference Driven PublishingConference Driven Publishing
Conference Driven PublishingDave Cross
 
Conference Driven Publishing
Conference Driven PublishingConference Driven Publishing
Conference Driven PublishingDave Cross
 
Perl in the Internet of Things
Perl in the Internet of ThingsPerl in the Internet of Things
Perl in the Internet of ThingsDave Cross
 
Return to the Kingdom of the Blind
Return to the Kingdom of the BlindReturn to the Kingdom of the Blind
Return to the Kingdom of the BlindDave Cross
 
Github, Travis-CI and Perl
Github, Travis-CI and PerlGithub, Travis-CI and Perl
Github, Travis-CI and PerlDave Cross
 
Object-Oriented Programming with Perl and Moose
Object-Oriented Programming with Perl and MooseObject-Oriented Programming with Perl and Moose
Object-Oriented Programming with Perl and MooseDave Cross
 
Database Programming with Perl and DBIx::Class
Database Programming with Perl and DBIx::ClassDatabase Programming with Perl and DBIx::Class
Database Programming with Perl and DBIx::ClassDave Cross
 
Matt's PSGI Archive
Matt's PSGI ArchiveMatt's PSGI Archive
Matt's PSGI ArchiveDave Cross
 

Plus de Dave Cross (20)

Measuring the Quality of Your Perl Code
Measuring the Quality of Your Perl CodeMeasuring the Quality of Your Perl Code
Measuring the Quality of Your Perl Code
 
Apollo 11 at 50 - A Simple Twitter Bot
Apollo 11 at 50 - A Simple Twitter BotApollo 11 at 50 - A Simple Twitter Bot
Apollo 11 at 50 - A Simple Twitter Bot
 
Monoliths, Balls of Mud and Silver Bullets
Monoliths, Balls of Mud and Silver BulletsMonoliths, Balls of Mud and Silver Bullets
Monoliths, Balls of Mud and Silver Bullets
 
The Professional Programmer
The Professional ProgrammerThe Professional Programmer
The Professional Programmer
 
I'm A Republic (Honest!)
I'm A Republic (Honest!)I'm A Republic (Honest!)
I'm A Republic (Honest!)
 
Web Site Tune-Up - Improve Your Googlejuice
Web Site Tune-Up - Improve Your GooglejuiceWeb Site Tune-Up - Improve Your Googlejuice
Web Site Tune-Up - Improve Your Googlejuice
 
Modern Perl Web Development with Dancer
Modern Perl Web Development with DancerModern Perl Web Development with Dancer
Modern Perl Web Development with Dancer
 
Freeing Tower Bridge
Freeing Tower BridgeFreeing Tower Bridge
Freeing Tower Bridge
 
Error(s) Free Programming
Error(s) Free ProgrammingError(s) Free Programming
Error(s) Free Programming
 
Modern Web Development with Perl
Modern Web Development with PerlModern Web Development with Perl
Modern Web Development with Perl
 
Improving Dev Assistant
Improving Dev AssistantImproving Dev Assistant
Improving Dev Assistant
 
Conference Driven Publishing
Conference Driven PublishingConference Driven Publishing
Conference Driven Publishing
 
Conference Driven Publishing
Conference Driven PublishingConference Driven Publishing
Conference Driven Publishing
 
TwittElection
TwittElectionTwittElection
TwittElection
 
Perl in the Internet of Things
Perl in the Internet of ThingsPerl in the Internet of Things
Perl in the Internet of Things
 
Return to the Kingdom of the Blind
Return to the Kingdom of the BlindReturn to the Kingdom of the Blind
Return to the Kingdom of the Blind
 
Github, Travis-CI and Perl
Github, Travis-CI and PerlGithub, Travis-CI and Perl
Github, Travis-CI and Perl
 
Object-Oriented Programming with Perl and Moose
Object-Oriented Programming with Perl and MooseObject-Oriented Programming with Perl and Moose
Object-Oriented Programming with Perl and Moose
 
Database Programming with Perl and DBIx::Class
Database Programming with Perl and DBIx::ClassDatabase Programming with Perl and DBIx::Class
Database Programming with Perl and DBIx::Class
 
Matt's PSGI Archive
Matt's PSGI ArchiveMatt's PSGI Archive
Matt's PSGI Archive
 

Dernier

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 

Dernier (20)

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Modern Perl for Non-Perl Programmers

  • 2. Topics ● What is Modern Perl? ● Variables ● Flow control ● Subroutines ● References ● Context London Perl Workshop 30th November 2013
  • 3. Topics ● CPAN ● Useful Libraries – – Database Access – ● Object Oriented Programming Web Programming Further Information London Perl Workshop 30th 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
  • 8. Current Version ● 5.18.1 – ● 12 Aug 2013 5.20.0 due next spring – 5.19.6 – 20 Nov 2013 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
  • 41. Comparison Examples ● 62 > 42 # true ● '0' == (3 * 2) - 6 # true ● 'apple' gt 'banana' # false ● 'apple' == 'banana' # true(!) ● 1 + 2 == '3 bears' # true ● 1 + 2 == 'three' # false 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
  • 51. While ● ● Execute loop while a condition is true while (EXPR) { BLOCK } 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
  • 54. Unless ● unless ($lives) { die “Game over”; } 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
  • 57. Until ● ● ● ● Inverted while until ( EXPR ) { BLOCK } Exactly the same as while ( ! EXPR ) { BLOCK } 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
  • 83. CPAN
  • 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
  • 94. Subclassing ● package Point3D; use Moose; extends 'Point'; has 'z' => (isa => 'Int', is => 'rw'); after 'clear' => sub { my $self = shift; $self->z(0); }; London Perl Workshop 30th November 2013
  • 95. Subclassing ● extends 'Point' – ● Define which class we're a subclass of has 'z' => ( isa = 'Int', is => 'rw' ) – Adds new attribute 'z' 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
  • 102. More Attribute Properties ● lazy – ● trigger – ● Subroutine called after the attribute is set isa – ● Only populate attribute when queried Set the type of an attribute Many more 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
  • 105. Good and Bad ● Good – – ● Standardised Supports many databases Bad – SQL 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
  • 107. DBIx::Class ● DBI extension ● Define classes in Perl ● We write Perl ● DBIx::Class writes the SQL 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
  • 124. DBIx::Class::Schema::Loader ● Connects to database ● Queries metadata ● Generates class definitions ● Writes them to disk ● Command line program – dbicdump 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
  • 130. Dancer ● ● Route-based framework use Dancer; get '/' => sub { return 'Hello World”; }; dance; ● bin/app.pl London Perl Workshop 30th November 2013
  • 131. Catalyst ● MVC framework – Model, View, Controller ● Most popular Perl web framework ● Powerful ● Flexible 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
  • 137. Other Advantages ● Standardised development servers ● Easier testing ● Middleware 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
  • 162. Perl Books ● Beginning Perl – ● Curtis Poe Perl Testing – A Developers Notebook – Langworth, chromatic London Perl Workshop 30th November 2013
  • 163. Perl Books ● Modern Perl – ● chromatic Definitive Guide to Catalyst – Diment, Trout 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
  • 172. London Perl Workshop 30th November 2013