Slide 1

Slide 1 text

Perl Basics Mike Doherty @mikedoherty_ca

Slide 2

Slide 2 text

What you'll need  A supported version of perl (v5.14.0 or newer)  A POSIX OS (linux, mac – use bluenose if all else fails)  A text editor (nano, emacs, vi, gedit, padre, sublime...)  A shell, ideally bash $ perl -v This is perl 5, version 16, subversion 2 (v5.16.2)...

Slide 3

Slide 3 text

Learning objectives  The very first baby steps: – Find the Perl documentation – Understand Perl's characteristics – Basic Perl syntax – Variables and data types in Perl – Complex data structures

Slide 4

Slide 4 text

Perl documentation  perldoc perl – perldoc -f function – perldoc -q search-in-faq – perldoc Some::Module  http://perldoc.perl.org/  https://metacpan.org/

Slide 5

Slide 5 text

What is Perl?  High-level, general-purpose, dynamic, interpreted – Well-suited for text manipulation, network programming, web development, system administration, bioinformatics... – Swiss Army Chainsaw and/or Duct Tape of the Internet  Dynamic and dynamically-typed  Statically-scoped (there is also optional dynamic scope)  Practical > Beautiful  Supports both procedural and OO paradigms  Possibly the world's most impressive array of third-party modules (the CPAN)

Slide 6

Slide 6 text

Running Perl  Perl is the language; perl is the interpreter  Unsurprisingly, you say: – perl prog.pl for scripts – perl -E 'say “Hello world”' for one-liners  Surprisingly, just perl doesn't give you a repl – use perl -dE1 for that  Use -c to syntax-check your file

Slide 7

Slide 7 text

Basic syntax  As a scripting language, statements are executed straightforwardly; no main() needed.  Statements end with a ;  Comments begin with a # (no multiline comments)  Strings in “” or ''; numbers don't require quotes  Often parens around argument lists can be omitted: print(“Hello world”); # uses STDOUT print STDERR “Hello world”; # STDERR

Slide 8

Slide 8 text

Variables  Dynamic typing  Variable types: – Scalar (integer, floating-point, string, reference) – Array (each element is a scalar!) – Hash (associative array maps strings to scalars)

Slide 9

Slide 9 text

Scalars  A scalar is a single thing  Integer: $int = 4;  Floating point: $value = 4.5;

Slide 10

Slide 10 text

Working with numbers  The normal operations you expect: – + - * / ** – ++ += -- -+ *= – x is the repetition operator  Create scalars with values 5 and 10, and print their sum $five = 5; $ten = 10; say $five + $ten;  Print five, five times say 5 x 5;

Slide 11

Slide 11 text

Working with strings  Strings are enclosed in double-quotes or single-quotes  Double-quotes interpolate; single-quotes don't  Say Hello world say “Hello world”; say 'Hello world'; print “Hello world\n”; print 'Hello world\n';

Slide 12

Slide 12 text

How to “spell” quotes  Multiple ways to “spell” double- and single-quotes  Very useful  Pick whatever makes sense for your situation print “Hello world\n”; print “Nintendo\x{AE}\n”; print qq{Nintendo\x{AE}\n}; # qq is two quotes print qq(contains {}) # () delimiter

Slide 13

Slide 13 text

Comparison operators  Numbers – == != – < > <= >= – <=>  Strings – eq ne – lt gt le ge – cmp

Slide 14

Slide 14 text

Control flow if ( cond ) { ...; } elsif ( cond ) { ...; } else { ...; } cond ? true : false; unless ( cond ){ ...; } for ( list ) { $_; } foreach my $item ( list ) { $item; } for (expr; expr; expr) { ...; } while (cond) { ...; } until (cond) { ...; }

Slide 15

Slide 15 text

Are the two inputs the same?  <> reads a single line of input from STDIN  Which comparison operators should you use?  What happens if I say 5 for one input and “string” for the other? $one = <>; $two = <>; if ($one == $two) { say “equal”; else { say “not equal”; }

Slide 16

Slide 16 text

The Safety Net  By default, Perl lets you shoot yourself in the foot  use strict;  use warnings;  use autodie; # if doing I/O  use Try::Tiny; # for try/catch

Slide 17

Slide 17 text

Are the two inputs the same?  <> reads a single line of input  Which comparison operators should you use?  What happens if I say 5 for one input and “string” for the other? use strict; use warnings; my $one = <>; my $two = <>; if ($one eq $two) { say “equal”; else { say “not equal”; }

Slide 18

Slide 18 text

Context of a value  Data is evaluated in string, numeric, or boolean context  String: – Use something as a string, and it'll be stringified – If that's not possible, a warning will be emitted  Numeric – Use something as a number, and it'll be numified – If that's not possible, a warning will be emitted  Boolean: – undef, 0, and '' are false values; everything else is true  == forces numeric context; eq forces string context

Slide 19

Slide 19 text

Scoping  my declares a lexical variable, which will be all of them for us  Use local to declare a dynamically-scoped variable  Use our to declare a package-scoped variable

Slide 20

Slide 20 text

Arrays  Arrays represent a list of scalars  Dynamically resized  Interpolation gives the string formed by each element, joined with spaces  Support queue/stack operations: – Left/low end: shift/unshift – Right/high end: push/pop  Declare with @array = (1, 2, 3);  Access with $array[$idx];

Slide 21

Slide 21 text

Working with Arrays  Declare an array of strings, and print each one on it's own line my @strings = qw( Mike Doherty ); foreach my $line (@strings) { say $line; } for (@strings) { say } say for @strings;

Slide 22

Slide 22 text

Context of an expression  Perl has a notion of “context” which describes something about the calling context  Void, scalar, list  In list context, an array is the contents of the array  In scalar context, an array is the length of the array my @a = (1, 2, 3); say @a; say scalar @a; say $#a;

Slide 23

Slide 23 text

Array “slices”  Extract a list of items from an array  “All the items between index 2 and 10”  “Indexes 1, 3, 4, 10, and 100” my @array = (0..9); # range operator say @array; # 0123456789 say $array[0]; # 0 say @array[0]; # slice of length 1 say @array[1,2,3]; # 123 say @array[1..3,8]; # 1238

Slide 24

Slide 24 text

Hashes  Hashes are hash tables, or associative arrays  Key-value pairs map strings to scalars in no particular order  Like arrays, expand dynamically to fit their contents my %h = ( 'key' => 'value' ); say $h{'key'}; $h{otherkey} = 10;  Extract the keys and values with... keys & values my %h = (key => value, otherkey => 10); say for keys %h;

Slide 25

Slide 25 text

Hash “slices”  Just like with arrays, but using keys instead of indexes my %h = ( one => 1, two => 2, three => 3, four => 4, five => 5, siz => 6 ); my @arr = @h{'one', 'three', 'five'}; say “@arr”;

Slide 26

Slide 26 text

References, a special kind of scalar  Scalars can be numbers, strings, or references  A reference is a kind of scalar that refers (or points to) another variable (a scalar, array, or hash)  This is very much like C's pointers, except: – you cannot poke whatever memory you want – Perl references know what they refer to

Slide 27

Slide 27 text

Creating references  To create a reference, use the backslash operator on a variable: my @array = (1, 2, 3); my $array_ref = \@array;  Or, create an array reference with []: – my $array_ref = [1, 2, 3];  Or, create a hash reference with {}: – my $hash_ref = { a => 1, b => 2 };

Slide 28

Slide 28 text

Dereferencing  To dereference, you need to know what kind of thing the reference points to: – Scalars: ${ $scalar_ref } – Arrays: @{ $array_ref } – Hash: %{ $hash_ref }  Alternatively, use the -> notation to access contents of arrayrefs and hashrefs: – $array_ref->[0] – $hash_ref->{key}

Slide 29

Slide 29 text

Multi-level data structures  Since array elements are always scalars, you can't have an element be an array  But you can have it be an array reference  This is how you build complex data structures  To debug: use Data::Dumper; print Dumper {the => ['data', 'structure']}; #$VAR1 = { # 'the' => [ # 'data', # 'structure' # ] # };

Slide 30

Slide 30 text

Using multi-level data structures  Build me a two-dimensional array that gives the multiplication tables up to 10 times 10, and print it out in proper order my $table; foreach my $row (1..10) { foreach my $col (1..10) { $table->[$row][$col] = $row*$col; } } say “@{ $table->[$_] }” for 1..10;