Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Introduction to Perl

Introduction to Perl

This talk gives an introduction to Perl, covering:
- finding the Perl documentation
- understanding Perl's characteristics
- running Perl programs
- basic Perl syntax
- variables and data types
- complex data structures

I gave this talk at the Dalhousie Faculty of Computer Science FreeSchool in March 2013.

Mike Doherty

March 14, 2013
Tweet

More Decks by Mike Doherty

Other Decks in Technology

Transcript

  1. 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)...
  2. 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
  3. Perl documentation  perldoc perl – perldoc -f function –

    perldoc -q search-in-faq – perldoc Some::Module  http://perldoc.perl.org/  https://metacpan.org/
  4. 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)
  5. 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
  6. 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
  7. Variables  Dynamic typing  Variable types: – Scalar (integer,

    floating-point, string, reference) – Array (each element is a scalar!) – Hash (associative array maps strings to scalars)
  8. Scalars  A scalar is a single thing  Integer:

    $int = 4;  Floating point: $value = 4.5;
  9. 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;
  10. 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';
  11. 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
  12. Comparison operators  Numbers – == != – < >

    <= >= – <=>  Strings – eq ne – lt gt le ge – cmp
  13. 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) { ...; }
  14. 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”; }
  15. 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
  16. 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”; }
  17. 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
  18. 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
  19. 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];
  20. 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;
  21. 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;
  22. 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
  23. 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;
  24. 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”;
  25. 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
  26. 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 };
  27. 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}
  28. 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' # ] # };
  29. 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;