Modern Perl for Non-Perl Programmers
-
Upload
dave-cross -
Category
Technology
-
view
28.745 -
download
5
description
Transcript of Modern Perl for Non-Perl Programmers
London Perl Workshop30th November 2013
Topics
● What is Modern Perl?● Variables● Flow control● Subroutines● References● Context
London Perl Workshop30th November 2013
Topics
● CPAN● Useful Libraries
– Object Oriented Programming
– Database Access
– Web Programming
● Further Information
What isModern Perl?
London Perl Workshop30th November 2013
What is Modern Perl
● Not well defined● Can mean at least two things● Changes to core Perl syntax● Big additions to Perl's toolset
– Moose
– DBIx::Class
– Catalyst
● We will cover both
London Perl Workshop30th 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 Workshop30th 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 Workshop30th November 2013
Current Version
● 5.18.1– 12 Aug 2013
● 5.20.0 due next spring– 5.19.6
– 20 Nov 2013
Introductionto Perl
London Perl Workshop30th November 2013
Introduction to Perl
● Quick look at some Perl features● Differences from other languages● Variables● Flow control● Subroutines● Context
London Perl Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th November 2013
Sigils
● Punctuations marks indicate variable type● Scalars use $
– $doctor
● Arrays use @– @time_lords
● Hashes use %– %companions
London Perl Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 each\n";
London Perl Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th November 2013
Hash Variables
● Hashes implement “look-up tables” or “dictionaries”
● Initialised with a list● %french = ('one', 'un', 'two', 'deux', 'three', 'trois');
London Perl Workshop30th November 2013
Fat Comma
● The “fat comma” is easier to understand● %german = (one => 'ein', two => 'zwei', three => 'drei');
London Perl Workshop30th November 2013
Accessing Hash Values
● $three = $french{three};
● print $german{two};
● Note sigil change● For exactly the same reason
London Perl Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th November 2013
Using the Default Variable
● while (<$file>) { if (/regex/) { print; }}
● Three uses of $_
– Input
– Match
London Perl Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th November 2013
Flow Control in Perl
● Standard flow control statements– if/elsif/else
– for
– while
● Some less standard ones– unless
– foreach
– until
London Perl Workshop30th November 2013
If / Else
● if (EXPR) { BLOCK}
● if (EXPR) { BLOCK1} else { BLOCK2}
London Perl Workshop30th November 2013
If / Else
● if ($lives < 0) { die “Game over”;}
● if ($lives < 0) { die “Game over”;} else { print “You won!”;}
London Perl Workshop30th 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 Workshop30th November 2013
If / Elsif / Else
● if ($temp > 25) { print “Too hot”;} elsif ($temp < 10) { print “Too cold”;} else { print “Just right”;}
London Perl Workshop30th November 2013
For
● C-style for loop● for ( INIT; EXPR; INCR ) { BLOCK}
– Execute INIT
– If EXPR is false exit loop
– Execute BLOCK and INCR
– Retry EXPR
● Rarely used
London Perl Workshop30th November 2013
For
● for ( $x = 0; $x <=10 ; ++$x ) { print “$x squared is “, $x * $x;}
London Perl Workshop30th November 2013
While
● Execute loop while a condition is true● while (EXPR) { BLOCK}
London Perl Workshop30th November 2013
While
● while ($continue) { if (do_something_useful()) { print $interesting_value; } else { $continue = 0; }}
London Perl Workshop30th 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 Workshop30th November 2013
Unless
● unless ($lives) { die “Game over”;}
London Perl Workshop30th 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 Workshop30th November 2013
Foreach
● foreach my $x ( 1 .. 10 ) { print “$x squared is “, $x * $x;}
London Perl Workshop30th November 2013
Until
● Inverted while● until ( EXPR ) { BLOCK}
● Exactly the same as● while ( ! EXPR ) { BLOCK}
London Perl Workshop30th November 2013
Until
● until ($stop) { if (do_something_useful()) { print $interesting_value; } else { $stop = 1; }}
London Perl Workshop30th 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 Workshop30th November 2013
Statement Modifiers
● Condition at end of statement● Invert logic● Can be more readable
– help_text() if $option eq '-h'
– print “Game over” unless $lives
– print while <$filehandle>
● Omit condition brackets
London Perl Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th November 2013
Advanced References
● Perl objects are usually implemented as hash references– But they are “blessed”
● You can create references to subroutines– my $sub_ref = \&my_sub;$sub_ref->('some', 'parameters');
● Anonymous subroutines– my $sub_ref = sub { print “Boo” };$sub_ref->();
London Perl Workshop30th 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 Workshop30th 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 Workshop30th November 2013
List Context
● List assignments– @arr = some_function()
– ($x, $y, $z) = some_function()
– ($x) = some_function()
● Most built-in functions
London Perl Workshop30th November 2013
Subroutine Parameters
● A common error● sub something { my $arg = @_; ...}
● Should be● sub something { my ($arg) = @_; ...}
London Perl Workshop30th November 2013
Context Rules
● There are no general rules● Need to learn● Or read documentation
London Perl Workshop30th 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 Workshop30th November 2013
File Input Contexts
● The file input operator handles different contexts● $line = <$filehandle>;
● @lines = <$filehandle>;
● ($line) = <$filehandle>; # danger!
CPAN
London Perl Workshop30th November 2013
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 Workshop30th November 2013
Installing CPAN Modules
● Try your usual package repositories– yum
– apt-get
– ppm
● May not have the modules you want– Or may have slightly older versions
London Perl Workshop30th November 2013
Installing CPAN Modules
● Various command line tools– CPAN Shell (cpan)
– CPANPLUS (cpanp)
– CPANMinus (cpanm)
● Install dependencies too
Useful CPANLibraries
London Perl Workshop30th November 2013
Useful CPAN Libraries
● Powerful CPAN modules● Object-Oriented Programming● Database access
– Object Relational Mapping
● Web Development– MVC frameworks
– Server/application glue
London Perl Workshop30th 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 Workshop30th 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
– MOP - Meta Object Protocol
– Set of abstractions for components of an object system
– Classes, Objects, Methods, Attributes
● An example might help
London Perl Workshop30th November 2013
Moose Example
● package Point;use Moose;
has 'x' => (isa => 'Int', is => 'rw');has 'y' => (isa => 'Int', is => 'rw');
sub clear { my $self = shift; $self->x(0); $self->y(0);}
London Perl Workshop30th November 2013
Creating Attributes
● has 'x' => (isa => 'Int', is => 'rw')
– Creates an attribute called 'x'
– Constrained to be an integer
– Read-write
● has 'y' => (isa => 'Int', is => 'rw')
London Perl Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th November 2013
More Attribute Properties
● lazy– Only populate attribute when queried
● trigger– Subroutine called after the attribute is set
● isa– Set the type of an attribute
● Many more
London Perl Workshop30th 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 Workshop30th 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 Workshop30th November 2013
Good and Bad
● Good– Standardised
– Supports many databases
● Bad– SQL
London Perl Workshop30th 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 Workshop30th November 2013
DBIx::Class
● DBI extension● Define classes in Perl● We write Perl● DBIx::Class writes the SQL
London Perl Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th November 2013
Sample Schema Class
● package CD::Schema;use base qw/DBIx::Class::Schema/;
__PACKAGE__->load_namespaces();
1;
London Perl Workshop30th 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 Workshop30th November 2013
Listing Artists
● foreach my $artist (@artists) { say $artist->name;
foreach my $cd ($artist->cds) { say “\t”, $cd->title, ' (', $cd->year, ')'; }}
London Perl Workshop30th November 2013
Searching Artists
● my @davids = $artist_rs->search({ name => { like => 'David %' },});
● Powerful searching syntax
London Perl Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th November 2013
DBIx::Class::Schema::Loader
● Connects to database● Queries metadata● Generates class definitions● Writes them to disk● Command line program
– dbicdump
London Perl Workshop30th 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 Workshop30th 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 CDCDCD/SchemaCD/Schema/ResultCD/Schema/Result/Cd.pmCD/Schema/Result/Artist.pmCD/Schema.pm
London Perl Workshop30th 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 Workshop30th November 2013
Perl Web Frameworks
● Plenty to choose from on CPAN● Web::Simple
– Simple to install and use
● Dancer– Lightweight and flexible
● Mojolicious– “Next Generation Web Framework”
● Catalyst– Extremely powerful
London Perl Workshop30th 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 Workshop30th November 2013
Dancer
● Route-based framework● use Dancer;
get '/' => sub { return 'Hello World”;};
dance;
● bin/app.pl
London Perl Workshop30th November 2013
Catalyst
● MVC framework– Model, View, Controller
● Most popular Perl web framework● Powerful● Flexible
London Perl Workshop30th 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 Workshop30th November 2013
What's the Problem?
● Web apps run in many environments● CGI● mod_perl handler● FCGI● Etc...● All have different interfaces
London Perl Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th November 2013
Other Advantages
● Standardised development servers● Easier testing● Middleware
London Perl Workshop30th 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 Workshop30th November 2013
Reference to Subroutine
● my $app = sub { my $env = shift;
return [ 200, [ ‘Content-Type’,‘text/plain’ ], [ ‘Hello World’ ], ];};
London Perl Workshop30th November 2013
Reference to Subroutine
● my $app = sub { my $env = shift;
return [ 200, [ ‘Content-Type’,‘text/plain’ ], [ ‘Hello World’ ], ];};
London Perl Workshop30th November 2013
Hash Reference
● my $app = sub { my $env = shift;
return [ 200, [ ‘Content-Type’,‘text/plain’ ], [ ‘Hello World’ ], ];};
London Perl Workshop30th November 2013
Hash Reference
● my $app = sub { my $env = shift;
return [ 200, [ ‘Content-Type’,‘text/plain’ ], [ ‘Hello World’ ], ];};
London Perl Workshop30th November 2013
Return Array Reference
● my $app = sub { my $env = shift;
return [ 200, [ ‘Content-Type’,‘text/plain’ ], [ ‘Hello World’ ], ];};
London Perl Workshop30th November 2013
Return Array Reference
● my $app = sub { my $env = shift;
return [ 200, [ ‘Content-Type’,‘text/plain’ ], [ ‘Hello World’ ], ];};
London Perl Workshop30th 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 Workshop30th November 2013
plackup
● Test PSGI server● $ plackup app.psgiHTTP::Server::PSGI: Accepting connections at http://localhost:5000/
London Perl Workshop30th 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 Workshop30th 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 Workshop30th November 2013
Middleware Example
● $ HEAD http://localhost:5000200 OKDate: Tue, 20 Jul 2010 20:25:52 GMTServer: HTTP::Server::PSGIContent-Length: 11Content-Type: text/plainClient-Date: Tue, 20 Jul 2010 20:25:52 GMTClient-Peer: 127.0.0.1:5000Client-Response-Num: 1X-Runtime: 0.000050
London Perl Workshop30th November 2013
Plack::App::*
● Ready-made solutions for common situations● Plack::App::CGIBin
– cgi-bin replacement
● Plack::App::Directory– Serve files with directory index
● Plack::App::URLMap– Map apps to different paths
London Perl Workshop30th 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 Workshop30th 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 Workshop30th November 2013
PSGI Server Support
● nginx support● mod_psgi● Plack::Handler::Apache2
London Perl Workshop30th November 2013
PSGI Server Support
● Many new web servers support PSGI● Starman, Starlet, Twiggy, Corona,
HTTP::Server::Simple::PSGI● Perlbal::Plugin::PSGI
London Perl Workshop30th 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
FurtherInformation
London Perl Workshop30th November 2013
Further Information
● Very high-level overview● Lots of information available
– Perl documentation
– Books
– Web sites
– Mailing lists
– User groups
– Conferences
London Perl Workshop30th 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 Workshop30th November 2013
Perldoc Options
● Documentation for a particular function– perldoc -f print
● Documentation for a particular variable– perldoc -v @_
● Search the FAQ for a keyword– perldoc -q sort
London Perl Workshop30th November 2013
Perl Books
● Essential Perl books● Learning Perl (6ed)
– Schwartz, Phoenix and foy
● Programming Perl (4ed)– Wall, Christiansen, Orwant and foy
● Perl Best Practices– Damian Conway
London Perl Workshop30th November 2013
Perl Books
● Effective Perl Programming– Hall, McAdams and foy
● Intermediate Perl (2ed)– Schwartz, foy and Phoenix
● Mastering Perl– brian d foy
London Perl Workshop30th November 2013
Perl Books
● Beginning Perl– Curtis Poe
● Perl Testing – A Developers Notebook– Langworth, chromatic
London Perl Workshop30th November 2013
Perl Books
● Modern Perl– chromatic
● Definitive Guide to Catalyst– Diment, Trout
London Perl Workshop30th November 2013
Perl Web Sites
● Perl home page– www.perl.org
● Perl documentation– perldoc.perl.org
● CPAN– metacpan.org
London Perl Workshop30th November 2013
Perl Web Sites
● Perl News– perlnews.org
● Perl Blogs– blogs.perl.org
– ironman.enlightenedperl.org
● Perl Foundation– perlfoundation.org
London Perl Workshop30th 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 Workshop30th November 2013
Perl Mailing Lists
● Dozens of lists– lists.perl.org
● Perl Weekly– perlweekly.com
London Perl Workshop30th 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 Workshop30th 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 Workshop30th 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 Workshop30th November 2013
The End
● Thank you for coming● Hope you enjoyed it● Hope it was useful● Any questions?
London Perl Workshop30th November 2013