Salt Lake Perl Mongers
http://saltlake.pm.org
David Oswald
daoswald@gmail.com
Add Perl To Your Toolbelt
Salt Lake Perl Mongers
http://saltlake.pm.org
David Oswald
daoswald@gmail.com
Add Perl To Your Toolbelt
Salt Lake Perl Mongers
http://saltlake.pm.org
David Oswald
daoswald@gmail.com
Add Perl To Your Toolbelt
Salt Lake Perl Mongers
● The local “Perl Community”
– Monthly meetings.
– Partnership discounts.
– Job announcements.
– Ev...
Who am I?
●
Dave Oswald.
● Studied Economics and Computer Science at U of U.
– Also CS in High School, SLCC, LAVC, and sel...
Our Goal
● Learn how (and why) to get started with Perl...
...in about two days.
But...But...
“It's an old language.”
First Appeared Most Recent Standard / Version
C 1972 2011 C11
Java 1995 2016 (est) JSE9
Objective-C 1983 2014? 2.0
C++ 198...
Conclusion
We can't draw useful conclusions based on a
programming language's age.
Should I just wait for Perl 6?
Should I just wait for Perl 6?
(No, they're different languages.)
● Perl5
– In use in production.
– Ships with Linux.
– Pe...
“The syntax is ugly.”
Quotes:
● “I'm supposed to learn___________for work ... it's really
bugging me. I don't think I've ever seen such an ugly
...
Quotes:
● “I'm supposed to learn Objective-C for work ... it's really
bugging me. I don't think I've ever seen such an ugl...
Quotes:
● The Homoiconic nature of ____
means that one cannot tell by
looking at the code alone whether
something is a dat...
Quotes:
● The Homoiconic nature of Lisp
means that one cannot tell by
looking at the code alone whether
something is a dat...
Do we need to talk about C++ and C syntax?
We can't draw conclusions based on
perceived syntactic beauty.
“Perl lacks subroutine signatures, or named
parameters.”
my( $who, $cares ) = @_;
my( $who, $cares ) = @_;
(This is real Perl 
5.20 syntax)
...see?
use v5.20;
use feature 'signatures';
sub foo ($left, $right) {
    return $left + $right;
}
So, why Perl?
The Three Virtues
The Three Virtues...
● “The Triumph of the Virtues”
– Andrea Mantegna, 1497
● Justice!
● Temperance!
● Fortitude!
The Three Virtues...
● “The Triumph of the Virtues”
– Andrea Mantegna, 1497
● Justice!
● Temperance!
● Fortitude!
The Three Virtues...of Programmers
The Three Virtues...of Programmers
● Laziness
The Three Virtues...of Programmers
● Laziness
– The quality that
makes you go to
great effort to
reduce overall
energy exp...
Impatience!
The Three Virtues...of Programmers
● Laziness
● Impatience
The Three Virtues...of Programmers
● Laziness
● Impatience
– The anger you feel when
the computer is being
lazy, which hap...
The Three Virtues...of Programmers
● Laziness
● Impatience
● Hubris
The Three Virtues...of Programmers
● Laziness
● Impatience
● Hubris
– The pride that makes
you write and maintain
programs...
The Three Virtues...of Programmers
● Laziness
– ...makes you go to great effort to reduce
your overall energy expenditure....
So... Who am I?
●
Dave Oswald.
● Studied Economics and Computer Science at U of U.
– Also CS in High School, SLCC, LAVC, I...
I am...
● Dave Oswald.
● Studied Economics and Computer Science at U of U.
– Also CS in High School, SLCC, LAVC, Independe...
So, why Perl?
Because...
Like vi(m), you probably already have it.
With Perl you can...With Perl you can...
...get the job done quickly....get the job done quickly.
With Perl you can...With Perl you can...
●
Be Expressive.Be Expressive.
Perl is...Perl is...
●
Powerful, with finesse.Powerful, with finesse.
Perl isPerl is
FUN!FUN!
Why Perl?
● It will get the job done quickly.
● It's expressive.
● It's powerful.
● It's fun.
● CPAN.
“...easy things should be easy, and hard things
should be possible.”
– Programming Perl, 4th
ed.
Obtaining Perl
Obtaining Perl
● Often it's already installed
– Your “System Perl”
Obtaining Perl
● Often it's already installed
– Your “System Perl”
● Package managers
– .rpm's, .deb's
Obtaining Perl
● Often it's already installed
– Your “System Perl”
● Package managers
– .rpm's, .deb's
● Perlbrew
– http:/...
Obtaining Perl
● Often it's already installed
– Your “System Perl”
● Package managers
– .rpm's, .deb's
● Perlbrew
– http:/...
Obtaining Perl
● Often it's already installed
– Your “System Perl”
● Package managers
– .rpm's, .deb's
● Perlbrew
– http:/...
Becoming ProductiveBecoming Productive
with Perlwith Perl
“What you must do - in any language - is to pick a
subset, get working writing code, and gradually
learn more of the langu...
Our Subset
● Structure
●
Data types
●
Operators
●
Lexical variables
●
Loops
● Conditionals
●
Subroutines
●
Files and Basic...
But first, perlintro
The Format
● A simple text file
– Whitespace is mostly insignificant, but encouraged.
#!/usr/bin/env perl
# comments
use Q...
The obligatory Hello World!
#!/usr/bin/perl
print “Hello world!n”;
– Save as 'hello', set executable, and invoke as: ./hel...
Be Strict!
#!/usr/bin/env perl
use strict;
use warnings;
use autodie;
use diagnostics;
Be Modern!
#!/usr/bin/env perl
use strict;
use warnings;
use diagnostics;
use autodie;
use feature ':5.22';     # or use 5...
Containers
● Scalar containers start with $, and hold one thing.
my $num = 1;
my $string = “Hello”
my $ref = $num;
Containers
● Scalars
● Array containers start with @, and hold zero or more scalars,
indexed by integers.
my @things = qw(...
Containers
● Scalars
● Arrays
● Hashes start with %, and hold zero or more values, indexed by keys.
my %set = ( seat => 5,...
Containers
● Scalars
– Single items.
● Arrays
– Lists of items.
● Hashes
– Collections of values indexed by keys.
Aggregate vs Scalar
● Aggregate types: @, %
● Scalar types: $
The Sigil expresses the container type
● $scalar # Scalar containers start with $
● @array # Array containers start with @...
Containers can hold references
@structure = (
[ 'a', 'b', 'c' ],
[ 'd', 'e', 'f' ],
{ 'g' => 42 },
);
print “$structure[2]...
Containers can hold references
@structure = (
[ 'a', 'b', 'c' ],
[ 'd', 'e', 'f' ],
{ 'g' => 42 },
);
print “$structure[2]...
Hash of arrays
%hash = (
names => [ qw/ bob frank joe / ],
ages => [ 34, 26, 46 ],
);
print $hash{names}[0], “n”;
print $h...
Hash of arrays
%hash = (
names => [ qw/ bob frank joe / ],
ages => [ 34, 26, 46 ],
);
print $hash{names}[0], “n”; # bob
pr...
Array of hashes
@array = (
{ name => joe, age => 34 },
{ name => pete, age => 26 }
);
print $array[0]{name}, “n”;
Array of hashes
@array = (
{ name => joe, age => 34 },
{ name => pete, age => 26 }
);
print $array[0]{name}, “n”; # joe
Hash of hashes
%hash = (
bob => { age => 34, sex => 'm' },
joe => { age => 26, sex => 'm' },
jane => { age => 30, sex => '...
Hash of hashes
%hash = (
bob => { age => 34, sex => 'm' },
joe => { age => 26, sex => 'm' },
jane => { age => 30, sex => '...
Scalar references to an arrays
my $aref =
[ qw/ a b c / ];
print “$aref->[1]n”;
$aref = @array;
Scalar references to an arrays
my $aref =
[ qw/ a b c / ];
print “$aref->[1]n”;
# b
$aref = @array;
Reference Constructors
● 
– Takes a reference to some
entity.
● [ … ]
– Constructs a reference to an
anonymous array.
● { ...
Topic containers
● $_ : The “it” or “topic” variable.
for( 1 .. 100 ) { print “$_n”; }
● @_ : The “subroutine parameters” ...
Many functions operate on $_ by default
● print $_ for 1 .. 10
● print for 1 .. 10
● while(<>) { chomp; print; }
● print i...
Many functions operate on $_ by default
● print $_ for 1 .. 10 #12345678910
● print for 1 .. 10 # 12345678910
● while(<>) ...
Data Types
Perl Data Types
● Strings
– “Hello world!n”
– 'Good morning Starshine...'
– '42'
● Numbers
42
3.141592654
2.9979e+08
0xFF
...
A few others
● References
– Created with , [...], or {...}
– Dereferenced with ${...}, @{...}, %{...}, or ->
● File handle...
Perl Data Types DWYM
● (Do What You Mean)
– Duck Typing
say '42' – 42;
0
say substr(42,0,1)
4
say 'oops' if '0';
– (String...
Booleans: What is the truth?
● 0 : (Numeric 0) False
● “0” : (String 0) False
● “” : (Empty string) False
● undef : (Undef...
Structure
Subroutines
sub add {
my @param = @_;
return $param[0] + $param[1];
}
sub fact {
my $n = shift();
return 1 if $n <= 1;
ret...
Namespaces
package Foo;
sub bar { return 1; }
our $baz = “Hello.”;
package main;
print $Foo::baz, “ “, Foo::bar();
Namespaces
package Foo;
sub bar { return 1; }
our $baz = “Hello.”;
package main;
print $Foo::baz, “ “, Foo::bar();
# Hello...
Package Globals
● Variables that aren't lexical (my) are package globals.
– Declare with 'our'.
our @family = qw( Dave Ail...
LoopingLooping
Loops (foreach and for)
foreach my $item (@list) {print “$itemn”;}
for (my $i=0; $i!=10; ++$i) {print “$in”;}
say for 1 .....
Loops (foreach and for)
foreach my $item (@list) {print “$itemn”;}
for (my $i=0; $i!=10; ++$i) {print “$in”;}
say for 1 .....
Loops (foreach and for)
foreach my $item (@list) {print “$itemn”;}
for (my $i=0; $i!=10; ++$i) {print “$in”;}
say for 1 .....
Loops (while and until)
while(rand(5) > 3) {print “Unlucky.n”;}
print while <>;
do {print “Greetings.n”} while (guests());...
Breakout!
for(1 .. 10) {
next if $_ == 5;
print $_, “n”;
last if $_ == 8;
}
Breakout!
for(1 .. 10) {
next if $_ == 5;
print $_, “n”;
last if $_ == 8;
}
● 1 2 3 4 6 7 8
Files
open my $in_fh, '<', 'myfile.txt' or die $!;
while( my $line = <in_fh> ) {
chomp $line;
print “$linen” if $line eq '...
Conditionals (if)
if(alive()) {
live_life();
}
elsif (dead()) {
haunt();
}
else {
# Undead?
drink_blood();
}
Conditionals
unless (dead()) {stayin_alive()}
snore() if $sleeping;
sleep() unless $time > $wakeup_time;
$can_continue and...
String vs Numeric Relational Operators
● 3 < 5
● 6.7 == 42
● “abcd” lt “bcde”
● “abcd” eq “abcd”
● Numeric:
==, <, >, <=, ...
String vs Numeric Relational Operators
● 3 < 5 # true
● 6.7 == 42 # false
● “abcd” lt “bcde” #true
● “abcd” eq “abcd” # tr...
Context: Scalar, or List
my $quantity = @camels;   # Scalar context.
my @elements = @array;    # List context.
my $item = ...
Context
● @array: List of elements, or element count.
● %hash: List of keys=>values, or Boolean “populated/empty”
● (1,2,3...
Scope
my $foo = 10;
{
my $foo = 100;
print $foo, “n”;
sub closure {return $foo}
print closure(), “n”;
}
print $foo, “n”;
p...
Scope
my $foo = 10;
{
my $foo = 100;
print $foo, “n”;         # 100
sub closure {return $foo}
print closure(), “n”;    # 1...
Functional loops
my @times_five = map {$_ * 5} @numbers;
my @filtered = grep {$_ =~ /^Y/i} @strings;
my @sorted = sort {$b...
Is it Perl or Lisp?
my @sorted = 
map  { $_­>[0]             } 
sort { $a­>[1] cmp $b­>[1] } 
map  { [ $_ => lc $_ ]     }...
Schwartzian Transform:
decorate/sort/undecorate idiom
my @sorted = 
map  { $_­>[0]             } 
sort { $a­>[1] cmp $b­>[...
Regular Expressions
Regular Expressions
$string =~ m/pattern/ #matching
$_      =~ m/pattern/
           m/pattern/
            /pattern/
$str...
It's the “It” variable again: $_
m/pattern/ matches against $_ by default.
s/pattern/replacement/ substitutes within $_ by...
Binding other variables: =~
$string =~ m/pattern/
$string =~ /pattern/ # “m” is usually optional.
$string =~ s/pattern/rep...
In scalar context: Boolean
if( $string =~ m/^Hello/ ) {
print “Hello to you to!n”;
}
In scalar context: Boolean
$string = 'You said “Hello.”';
if( $string =~ m/^Hello/ ) {
print “Hello to you to!n”;
}
Captures returned in list context
say for “abcde” =~ m/(.)(.)(.)/;
Captures returned in list context
say for “abcde” =~ m/(.)(.)(.)/;
a
b
c
Captures also populate $1, $2 ...
my $string = “abcde”;
if( $string =~ m/(.)(.)(.)/ ) {
print “$1$2$3n”;
}
Captures also populate $1, $2 ...
my $string = “abcde”;
if( $string =~ m/(.)(.)(.)/ ) {
print “$1$2$3n”;
}
abc
/g modifier
while( “abcde” =~ m/(.)/g ) {
print “$1n”;
}
/g modifier
while( “abcde” =~ m/(.)/g ) {
print “$1n”;
}
a
b
c
d
e
Using Core Modules
use strict;
use warnings;
use feature qw(say);
use List::Util 'reduce';
say reduce { $a + $b } ( 0,1, 2...
Using Core Modules
use strict;
use warnings;
use feature qw(say);
use List::Util 'reduce';
say reduce { $a + $b } ( 0,1, 2...
CPANCPAN
Search CPAN
Using CPAN
$ cpan install Mojolicious;
#!/usr/bin/env perl
use Mojolicous::Lite;
get '/' => { text => 'Hello world!' };
ap...
Using CPAN
$ cpan install
Mojolicious;
#!/usr/bin/env perl
use Mojolicous::Lite;
get '/' => {
text => 'Hello world!'
};
ap...
“A concept is valid in Perl only if it can be shown to work in one line.”
perl ­Mojo ­E 'a("/" => {text => "Hello World!"}...
Reading
● Learning Perl
● Intermediate Perl
● Programming Perl
● Modern Perl
● perldoc
“You can sometimes write faster code in C, but
you can always write code faster in Perl.”
– perldoc perlembed
Slides avail...
Add Perl to Your Toolbelt
Add Perl to Your Toolbelt
Add Perl to Your Toolbelt
Add Perl to Your Toolbelt
Upcoming SlideShare
Loading in …5
×

Add Perl to Your Toolbelt

618 views

Published on

Introduction to Perl Programming (OpenWest 2014).

A 90 minute introduction to the why and how of becoming productive with the Perl Programming Language.

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
618
On SlideShare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
Downloads
7
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • Let&amp;apos;s stop here and try.
  • When should we use a hash? An array?
  • Arrays are ordered. Hashes are not.
  • Add Perl to Your Toolbelt

    1. 1. Salt Lake Perl Mongers http://saltlake.pm.org David Oswald daoswald@gmail.com Add Perl To Your Toolbelt
    2. 2. Salt Lake Perl Mongers http://saltlake.pm.org David Oswald daoswald@gmail.com Add Perl To Your Toolbelt
    3. 3. Salt Lake Perl Mongers http://saltlake.pm.org David Oswald daoswald@gmail.com Add Perl To Your Toolbelt
    4. 4. Salt Lake Perl Mongers ● The local “Perl Community” – Monthly meetings. – Partnership discounts. – Job announcements. – Everyone learns and grows. – For the love of Perl! ● http://saltlake.pm.org
    5. 5. Who am I? ● Dave Oswald. ● Studied Economics and Computer Science at U of U. – Also CS in High School, SLCC, LAVC, and self-guided. ● Endurance International Group / Bluehost. – Focus on back-end development with Perl. ● Solving problems programatically is my hobby. Gratifyingly, it's also my job. ● daoswald@gmail.com - david.oswald@endurance.com ● Salt Lake Perl Mongers – http://saltlake.pm.org
    6. 6. Our Goal ● Learn how (and why) to get started with Perl... ...in about two days.
    7. 7. But...But...
    8. 8. “It's an old language.”
    9. 9. First Appeared Most Recent Standard / Version C 1972 2011 C11 Java 1995 2016 (est) JSE9 Objective-C 1983 2014? 2.0 C++ 1983 2014 C++14 Visual Basic 1991 2015 14.0 (.net) C# 2000 2015 6.0 PHP 1995 2016 7.0.4 Python 1991 Python 2 2015 2.7.11 Python 3 2015 3.5.1 JavaScript 1995 2011 1.8.5 ECMAScript 1997 2015 6 Perl 1987 Perl 5 1994 2015 5.22.1 (5.24 due in June 2016)
    10. 10. Conclusion We can't draw useful conclusions based on a programming language's age.
    11. 11. Should I just wait for Perl 6?
    12. 12. Should I just wait for Perl 6? (No, they're different languages.) ● Perl5 – In use in production. – Ships with Linux. – Performant. – Stable. – Ongoing maintenance. – Ongoing new features. – CPAN. – Often steals features from Perl 6. ● Perl 6 – Still lives in its lab cage. – Can be compiled / installed. – Still not well optimized. – Still in flux. – Not yet feature complete. – Many. – Some key libraries. – Invents revolutionary concepts.
    13. 13. “The syntax is ugly.”
    14. 14. Quotes: ● “I'm supposed to learn___________for work ... it's really bugging me. I don't think I've ever seen such an ugly programming language.
    15. 15. Quotes: ● “I'm supposed to learn Objective-C for work ... it's really bugging me. I don't think I've ever seen such an ugly programming language.
    16. 16. Quotes: ● The Homoiconic nature of ____ means that one cannot tell by looking at the code alone whether something is a data structure or a function. You have to read and understand the context. Other languages make it pretty clear because they use different symbols and syntax for each.
    17. 17. Quotes: ● The Homoiconic nature of Lisp means that one cannot tell by looking at the code alone whether something is a data structure or a function. You have to read and understand the context. Other languages make it pretty clear because they use different symbols and syntax for each.
    18. 18. Do we need to talk about C++ and C syntax?
    19. 19. We can't draw conclusions based on perceived syntactic beauty.
    20. 20. “Perl lacks subroutine signatures, or named parameters.”
    21. 21. my( $who, $cares ) = @_;
    22. 22. my( $who, $cares ) = @_; (This is real Perl  5.20 syntax)
    23. 23. ...see? use v5.20; use feature 'signatures'; sub foo ($left, $right) {     return $left + $right; }
    24. 24. So, why Perl?
    25. 25. The Three Virtues
    26. 26. The Three Virtues... ● “The Triumph of the Virtues” – Andrea Mantegna, 1497 ● Justice! ● Temperance! ● Fortitude!
    27. 27. The Three Virtues... ● “The Triumph of the Virtues” – Andrea Mantegna, 1497 ● Justice! ● Temperance! ● Fortitude!
    28. 28. The Three Virtues...of Programmers
    29. 29. The Three Virtues...of Programmers ● Laziness
    30. 30. The Three Virtues...of Programmers ● Laziness – The quality that makes you go to great effort to reduce overall energy expenditure.
    31. 31. Impatience!
    32. 32. The Three Virtues...of Programmers ● Laziness ● Impatience
    33. 33. The Three Virtues...of Programmers ● Laziness ● Impatience – The anger you feel when the computer is being lazy, which happens when another programmer is not lazy.
    34. 34. The Three Virtues...of Programmers ● Laziness ● Impatience ● Hubris
    35. 35. The Three Virtues...of Programmers ● Laziness ● Impatience ● Hubris – The pride that makes you write and maintain programs that you can be proud of, and that your peers will admire.
    36. 36. The Three Virtues...of Programmers ● Laziness – ...makes you go to great effort to reduce your overall energy expenditure. – …makes you write robust, modular, well- documented programs so you can reuse [the effort]. ● Impatience – ...anger you feel when the computer is being lazy, which happens when another programmer is not lazy. – ...makes you write programs that use minimal code so they’re fast, efficient, and anticipate what needs to be done. ● Hubris – ...pride that makes you write and maintain programs that you and your peers will admire. – ...uncontrolled or undeserved, it can also get you in trouble.
    37. 37. So... Who am I? ● Dave Oswald. ● Studied Economics and Computer Science at U of U. – Also CS in High School, SLCC, LAVC, Independent. ● Endurance International Group / Bluehost. – Focus on back-end development with Perl. ● Solving problems programatically is my hobby. Gratifyingly, it's also my job. ● daoswald@gmail.com – david.oswald@endurance.com ● Salt Lake Perl Mongers – http://saltlake.pm.org
    38. 38. I am... ● Dave Oswald. ● Studied Economics and Computer Science at U of U. – Also CS in High School, SLCC, LAVC, Independent. ● Endurance International Group / Bluehost. – Focus on Back-end development with Perl. ● Solving problems programatically is my hobby. Gratifyingly, it's also my job. ● daoswald@gmail.com ● Salt Lake Perl Mongers – http://saltlake.pm.org ● Aspiring to be: – Lazy – Impatient – Hubristic
    39. 39. So, why Perl?
    40. 40. Because...
    41. 41. Like vi(m), you probably already have it.
    42. 42. With Perl you can...With Perl you can... ...get the job done quickly....get the job done quickly.
    43. 43. With Perl you can...With Perl you can... ● Be Expressive.Be Expressive.
    44. 44. Perl is...Perl is... ● Powerful, with finesse.Powerful, with finesse.
    45. 45. Perl isPerl is FUN!FUN!
    46. 46. Why Perl? ● It will get the job done quickly. ● It's expressive. ● It's powerful. ● It's fun. ● CPAN.
    47. 47. “...easy things should be easy, and hard things should be possible.” – Programming Perl, 4th ed.
    48. 48. Obtaining Perl
    49. 49. Obtaining Perl ● Often it's already installed – Your “System Perl”
    50. 50. Obtaining Perl ● Often it's already installed – Your “System Perl” ● Package managers – .rpm's, .deb's
    51. 51. Obtaining Perl ● Often it's already installed – Your “System Perl” ● Package managers – .rpm's, .deb's ● Perlbrew – http://perlbrew.pl
    52. 52. Obtaining Perl ● Often it's already installed – Your “System Perl” ● Package managers – .rpm's, .deb's ● Perlbrew – http://perlbrew.pl ● Strawberry Perl – MS Windows – http://strawberryperl.com
    53. 53. Obtaining Perl ● Often it's already installed – Your “System Perl” ● Package managers – .rpm's, .deb's ● Perlbrew – http://perlbrew.pl ● Strawberry Perl – MS Windows – http://strawberryperl.com ● Active State – Windows – Support
    54. 54. Becoming ProductiveBecoming Productive with Perlwith Perl
    55. 55. “What you must do - in any language - is to pick a subset, get working writing code, and gradually learn more of the language, its libraries, and its tools.” – Bjarne Stroustrup http://www.stroustrup.com/bs_faq.html#big
    56. 56. Our Subset ● Structure ● Data types ● Operators ● Lexical variables ● Loops ● Conditionals ● Subroutines ● Files and Basic IO ● Using objects ● Using CPAN
    57. 57. But first, perlintro
    58. 58. The Format ● A simple text file – Whitespace is mostly insignificant, but encouraged. #!/usr/bin/env perl # comments use Quantum::Superpositions 'eigenstates'; use constant PI => 3.141592654; # Your app for world domination goes here.
    59. 59. The obligatory Hello World! #!/usr/bin/perl print “Hello world!n”; – Save as 'hello', set executable, and invoke as: ./hello ● or... perl ­e 'print “Hello world!n”' perl ­E 'say “Hello world!”' perl ­e 'printf “%sn”, “Hello world!”'
    60. 60. Be Strict! #!/usr/bin/env perl use strict; use warnings; use autodie; use diagnostics;
    61. 61. Be Modern! #!/usr/bin/env perl use strict; use warnings; use diagnostics; use autodie; use feature ':5.22';     # or use 5.022;
    62. 62. Containers ● Scalar containers start with $, and hold one thing. my $num = 1; my $string = “Hello” my $ref = $num;
    63. 63. Containers ● Scalars ● Array containers start with @, and hold zero or more scalars, indexed by integers. my @things = qw( this that and the other ); my @refs = ( $x, $y, [@z] ); print “$things[0]n”; # this print “$things[-1]n; # other
    64. 64. Containers ● Scalars ● Arrays ● Hashes start with %, and hold zero or more values, indexed by keys. my %set = ( seat => 5, hp => 250, fuel => 'reg' ); print “The car has $set{hp} horsepower.n”; print “There are “, scalar keys %set, “ elements.n”; my @keynames = keys %set; my @vals = values %set; if( exists $set{fuel} ) { ... }
    65. 65. Containers ● Scalars – Single items. ● Arrays – Lists of items. ● Hashes – Collections of values indexed by keys.
    66. 66. Aggregate vs Scalar ● Aggregate types: @, % ● Scalar types: $
    67. 67. The Sigil expresses the container type ● $scalar # Scalar containers start with $ ● @array # Array containers start with @ ● $array[5] # Array elements are scalar containers: $ ● %hash # Hashes start with % ● $hash{key} # Hash elements are scalar containers: $
    68. 68. Containers can hold references @structure = ( [ 'a', 'b', 'c' ], [ 'd', 'e', 'f' ], { 'g' => 42 }, ); print “$structure[2]{g}n”;
    69. 69. Containers can hold references @structure = ( [ 'a', 'b', 'c' ], [ 'd', 'e', 'f' ], { 'g' => 42 }, ); print “$structure[2]{g}n”; # 42
    70. 70. Hash of arrays %hash = ( names => [ qw/ bob frank joe / ], ages => [ 34, 26, 46 ], ); print $hash{names}[0], “n”; print $hash{ages}[0], “n”;
    71. 71. Hash of arrays %hash = ( names => [ qw/ bob frank joe / ], ages => [ 34, 26, 46 ], ); print $hash{names}[0], “n”; # bob print $hash{ages}[0], “n”; # 34
    72. 72. Array of hashes @array = ( { name => joe, age => 34 }, { name => pete, age => 26 } ); print $array[0]{name}, “n”;
    73. 73. Array of hashes @array = ( { name => joe, age => 34 }, { name => pete, age => 26 } ); print $array[0]{name}, “n”; # joe
    74. 74. Hash of hashes %hash = ( bob => { age => 34, sex => 'm' }, joe => { age => 26, sex => 'm' }, jane => { age => 30, sex => 'f' }, ); print $hash{bob}{age}, “n”; print $hash{joe}{sex}, “n”;
    75. 75. Hash of hashes %hash = ( bob => { age => 34, sex => 'm' }, joe => { age => 26, sex => 'm' }, jane => { age => 30, sex => 'f' }, ); print $hash{bob}{age}, “n”; # 34 print $hash{joe}{sex}, “n”; # f
    76. 76. Scalar references to an arrays my $aref = [ qw/ a b c / ]; print “$aref->[1]n”; $aref = @array;
    77. 77. Scalar references to an arrays my $aref = [ qw/ a b c / ]; print “$aref->[1]n”; # b $aref = @array;
    78. 78. Reference Constructors ● – Takes a reference to some entity. ● [ … ] – Constructs a reference to an anonymous array. ● { … } – Constructs a reference to an anonymous hash.
    79. 79. Topic containers ● $_ : The “it” or “topic” variable. for( 1 .. 100 ) { print “$_n”; } ● @_ : The “subroutine parameters” variable. sub sum { my $acc; $acc += shift @_ while @_; return $acc; }
    80. 80. Many functions operate on $_ by default ● print $_ for 1 .. 10 ● print for 1 .. 10 ● while(<>) { chomp; print; } ● print if m/pattern/
    81. 81. Many functions operate on $_ by default ● print $_ for 1 .. 10 #12345678910 ● print for 1 .. 10 # 12345678910 ● while(<>) { chomp; print; } ● print if m/pattern/
    82. 82. Data Types
    83. 83. Perl Data Types ● Strings – “Hello world!n” – 'Good morning Starshine...' – '42' ● Numbers 42 3.141592654 2.9979e+08 0xFF 0655
    84. 84. A few others ● References – Created with , [...], or {...} – Dereferenced with ${...}, @{...}, %{...}, or -> ● File handles – Internally implemented as Typeglobs. ● Typeglobs – Mostly for when we want to deal with the man behind the curtain.
    85. 85. Perl Data Types DWYM ● (Do What You Mean) – Duck Typing say '42' – 42; 0 say substr(42,0,1) 4 say 'oops' if '0'; – (String '0' is Boolean false)
    86. 86. Booleans: What is the truth? ● 0 : (Numeric 0) False ● “0” : (String 0) False ● “” : (Empty string) False ● undef : (Undefined values) False ● Everything that is not false is true. – Including the string “0E0”
    87. 87. Structure
    88. 88. Subroutines sub add { my @param = @_; return $param[0] + $param[1]; } sub fact { my $n = shift(); return 1 if $n <= 1; return $n * fact ( $n-1 ); }
    89. 89. Namespaces package Foo; sub bar { return 1; } our $baz = “Hello.”; package main; print $Foo::baz, “ “, Foo::bar();
    90. 90. Namespaces package Foo; sub bar { return 1; } our $baz = “Hello.”; package main; print $Foo::baz, “ “, Foo::bar(); # Hello. 1
    91. 91. Package Globals ● Variables that aren't lexical (my) are package globals. – Declare with 'our'. our @family = qw( Dave Aileen Nathaniel Noelle ); – Available within the same package. ● print “@familyn”; – Available globally via fully qualified name. ● print “@main::familyn”;
    92. 92. LoopingLooping
    93. 93. Loops (foreach and for) foreach my $item (@list) {print “$itemn”;} for (my $i=0; $i!=10; ++$i) {print “$in”;} say for 1 .. 10;
    94. 94. Loops (foreach and for) foreach my $item (@list) {print “$itemn”;} for (my $i=0; $i!=10; ++$i) {print “$in”;} say for 1 .. 10; # say what?
    95. 95. Loops (foreach and for) foreach my $item (@list) {print “$itemn”;} for (my $i=0; $i!=10; ++$i) {print “$in”;} say for 1 .. 10; # Implicit $_
    96. 96. Loops (while and until) while(rand(5) > 3) {print “Unlucky.n”;} print while <>; do {print “Greetings.n”} while (guests()); print “42n” until end_of_time();
    97. 97. Breakout! for(1 .. 10) { next if $_ == 5; print $_, “n”; last if $_ == 8; }
    98. 98. Breakout! for(1 .. 10) { next if $_ == 5; print $_, “n”; last if $_ == 8; } ● 1 2 3 4 6 7 8
    99. 99. Files open my $in_fh, '<', 'myfile.txt' or die $!; while( my $line = <in_fh> ) { chomp $line; print “$linen” if $line eq 'Hello!'; }
    100. 100. Conditionals (if) if(alive()) { live_life(); } elsif (dead()) { haunt(); } else { # Undead? drink_blood(); }
    101. 101. Conditionals unless (dead()) {stayin_alive()} snore() if $sleeping; sleep() unless $time > $wakeup_time; $can_continue and live(); # Logical short circuit live() or die “trying.”; # Logical Short circuit
    102. 102. String vs Numeric Relational Operators ● 3 < 5 ● 6.7 == 42 ● “abcd” lt “bcde” ● “abcd” eq “abcd” ● Numeric: ==, <, >, <=, >=, !=, <=> ● Stringwise: eq, lt, gt, le, ge, ne, cmp
    103. 103. String vs Numeric Relational Operators ● 3 < 5 # true ● 6.7 == 42 # false ● “abcd” lt “bcde” #true ● “abcd” eq “abcd” # true ● Numeric: ==, <, >, <=, >=, !=, <=> ● Stringwise: eq, lt, gt, le, ge, ne, cmp
    104. 104. Context: Scalar, or List my $quantity = @camels;   # Scalar context. my @elements = @array;    # List context. my $item = qw/ a b c /; # c (Scalar context.) my ($item) = qw/ a b c /; # a (List context.) foreach(@array) {… while($condition) { …
    105. 105. Context ● @array: List of elements, or element count. ● %hash: List of keys=>values, or Boolean “populated/empty” ● (1,2,3): List: (1,2,3), Scalar: 3 ● foreach( list )... ● while( scalar )... ● Most operators impose scalar context on operands. ● Comma doesn't.
    106. 106. Scope my $foo = 10; { my $foo = 100; print $foo, “n”; sub closure {return $foo} print closure(), “n”; } print $foo, “n”; print closure(), “n”;
    107. 107. Scope my $foo = 10; { my $foo = 100; print $foo, “n”;         # 100 sub closure {return $foo} print closure(), “n”;    # 100 } print $foo, “n”;        # 10 print closure(), “n”;   # 100
    108. 108. Functional loops my @times_five = map {$_ * 5} @numbers; my @filtered = grep {$_ =~ /^Y/i} @strings; my @sorted = sort {$b <=> $a} @unsorted;
    109. 109. Is it Perl or Lisp? my @sorted =  map  { $_­>[0]             }  sort { $a­>[1] cmp $b­>[1] }  map  { [ $_ => lc $_ ]     }  @unsorted;
    110. 110. Schwartzian Transform: decorate/sort/undecorate idiom my @sorted =  map  { $_­>[0]             }  sort { $a­>[1] cmp $b­>[1] }  map  { [ $_ => lc $_ ]     }  @unsorted;
    111. 111. Regular Expressions
    112. 112. Regular Expressions $string =~ m/pattern/ #matching $_      =~ m/pattern/            m/pattern/             /pattern/ $string =~ s/pattern/replacement/ #substitution $_      =~ s/pattern/replacement/            s/pattern/replacement/
    113. 113. It's the “It” variable again: $_ m/pattern/ matches against $_ by default. s/pattern/replacement/ substitutes within $_ by default.
    114. 114. Binding other variables: =~ $string =~ m/pattern/ $string =~ /pattern/ # “m” is usually optional. $string =~ s/pattern/replacement/
    115. 115. In scalar context: Boolean if( $string =~ m/^Hello/ ) { print “Hello to you to!n”; }
    116. 116. In scalar context: Boolean $string = 'You said “Hello.”'; if( $string =~ m/^Hello/ ) { print “Hello to you to!n”; }
    117. 117. Captures returned in list context say for “abcde” =~ m/(.)(.)(.)/;
    118. 118. Captures returned in list context say for “abcde” =~ m/(.)(.)(.)/; a b c
    119. 119. Captures also populate $1, $2 ... my $string = “abcde”; if( $string =~ m/(.)(.)(.)/ ) { print “$1$2$3n”; }
    120. 120. Captures also populate $1, $2 ... my $string = “abcde”; if( $string =~ m/(.)(.)(.)/ ) { print “$1$2$3n”; } abc
    121. 121. /g modifier while( “abcde” =~ m/(.)/g ) { print “$1n”; }
    122. 122. /g modifier while( “abcde” =~ m/(.)/g ) { print “$1n”; } a b c d e
    123. 123. Using Core Modules use strict; use warnings; use feature qw(say); use List::Util 'reduce'; say reduce { $a + $b } ( 0,1, 2, 3, 4, 5 );
    124. 124. Using Core Modules use strict; use warnings; use feature qw(say); use List::Util 'reduce'; say reduce { $a + $b } ( 0,1, 2, 3, 4, 5 ); # 15
    125. 125. CPANCPAN
    126. 126. Search CPAN
    127. 127. Using CPAN $ cpan install Mojolicious; #!/usr/bin/env perl use Mojolicous::Lite; get '/' => { text => 'Hello world!' }; app->start;
    128. 128. Using CPAN $ cpan install Mojolicious; #!/usr/bin/env perl use Mojolicous::Lite; get '/' => { text => 'Hello world!' }; app->start; ~/perlws/mymojoapp daemon curl http://localhost:3000 Hello world!
    129. 129. “A concept is valid in Perl only if it can be shown to work in one line.” perl ­Mojo ­E 'a("/" => {text => "Hello World!"})­>start' daemon curl http://localhost:3000 Hello World!
    130. 130. Reading ● Learning Perl ● Intermediate Perl ● Programming Perl ● Modern Perl ● perldoc
    131. 131. “You can sometimes write faster code in C, but you can always write code faster in Perl.” – perldoc perlembed Slides available on Slide Share: http://www.slideshare.net/daoswald/toolbelt David Oswald: daoswald@gmail.com

    ×