Perl Intro 01

Embed Size (px)

Citation preview

  • 8/3/2019 Perl Intro 01

    1/29

    Getting started in Perl:

    Intro to Perl for programmers

    Matthew Heusser xndev.com - [email protected]

    Presented to the West Michigan Perl Users Group

  • 8/3/2019 Perl Intro 01

    2/29

    Why use Perl?

    Discuss

  • 8/3/2019 Perl Intro 01

    3/29

    Getting Perl

    www.activestate.com

    The easy way to get started in Windows

    www.cpan.org (Comprehensive Perl ArchiveNetwork)

    Ifyou have Linux, chances are you have Perl

    Both support modules for almost everythingimaginable.

  • 8/3/2019 Perl Intro 01

    4/29

    My first Perl script

    #!/usr/bin/perl -wuse strict;print "Hello, world\n";

  • 8/3/2019 Perl Intro 01

    5/29

    Variables in Perl

    Scalars start with a $ ex: $foo

    Arrays start with a @ ex: @foo

    Hashs (Associative arrays) start with % ex:%foo

    By convention file handles are UPPERCASE

    (no funny character). my gives variable lexical (local) scope. Use

    this unless you have reason for some otherscope.

  • 8/3/2019 Perl Intro 01

    6/29

    Scalars

    A Scalar begins with a $

    A Scalarholds a single string, number or

    reference.

    Unitialized scalars are undef.

    Examples:

    my $num = 3.1412;

    $str = "This is a string";

  • 8/3/2019 Perl Intro 01

    7/29

    Type Safe

    Perl is a loosely-typed language

    To make a string, evaluate the scalar in

    string context Example: if ($a eq Fifty) { do_stuff($a); }

    To make a number, evaluate as a number

    Example: if ($a == 50) { do_stuff($a); }

    Conversion is like ATOI

    To guarantee output, use prinft or sprintf

  • 8/3/2019 Perl Intro 01

    8/29

    Some control structures

    Use {} (Curlies) to declare what your controlstrucuture is working with. Like BEGIN/END

    in PL/SQL or Pascal. Usual if-elsif (note missing e), while, and

    for structures.

    Also supports unless (!if), until (!while),and foreach strucutures.

    next; is like continue; in C.

    last; is like break; in C.

  • 8/3/2019 Perl Intro 01

    9/29

    Boolean context

    The scalars: (null string), 0, 0, and undefevaluate to false, everything else evalutates

    to true. Lists are put into scalar context, then

    evaluated for truth value. Zero length lists,and undef arrays evalute to false, all other

    lists are true.

  • 8/3/2019 Perl Intro 01

    10/29

    Some operators

    Perl supports the usual +,-,*,/,%,++,-- (add,substract, multiply, divide, modulo,

    increment, decrement). . (period) concatenates strings.

    C style +=, .= etc. are supported.

    Use ==, !=, >, >=,

  • 8/3/2019 Perl Intro 01

    11/29

    Basic I/O STDIN is a file

    To read from a file, do this:

    my $str = ;

    Control-Z is the EOF symbol on windows

    To re-direct STDIN from a file, do this:

    UNIX: perl scriptname.pl < in.txt

    Win: type in.txt | perl scriptname.pl

    To loop until EOF, do this:

    while (my $str = ) {

    }

  • 8/3/2019 Perl Intro 01

    12/29

    Exercise

    1) Write a program to add two scalar variablestogether and print the total.

    3) Write a program to:

    Read three numbers from the command line

    Add them up

    Print the total

    2) Mod the program to also print an average

  • 8/3/2019 Perl Intro 01

    13/29

    Arrays

    Array names begin with a @

    Arrays are composites of scalars that areindexed with numbers beginning with 0.

    Arrays are named Lists. Subtle differencesexist between Arrays and Lists.

    Examples:

    my @stuff = (1,2,3); # use @ for thecomposite

    $stuff[0] = 10; # use $ for a single element(scalar)

    $stuff[99] = Numbers and strings can be mixed;

  • 8/3/2019 Perl Intro 01

    14/29

    Iterating over a list

    for (my $i=0; $i< scalar(@a);$i++) {

    do_something($a[$i]);

    }

    for my $val (@a) {

    do_something($val);

    }

  • 8/3/2019 Perl Intro 01

    15/29

    Push and Pop

    my @a;

    push (@a, 2);

    push (@a, 3);

    my $var = pop(@a);

    Remember, lists are automatically managed

    A stack using arrays is now trivial

    I sure wish I had this for the AP computer science Atest!

  • 8/3/2019 Perl Intro 01

    16/29

    Exercises

    1) Write a program to:

    Read three numbers from the commandline

    Into a list

    Loop and re-print the numbers

    Print the total

    2) Print the numbers in reverse

    Its ok to use a c-style for loop

  • 8/3/2019 Perl Intro 01

    17/29

    Hashes

    Hash names begin with %

    Hashes are composites of scalars that are indexedwith scalars.

    Hashes are unordered.

    Example:

    my %employee;

    $employee{"name"} = "Bill Day";$employee{"SSN"} = "353-27-7625";

    print $employee{"name"}, $employee{"SSN"}

    - Outputs: Bill Day353-27-7625

  • 8/3/2019 Perl Intro 01

    18/29

    Scalar vs List Context

    In an assignment, context is determined byleft side of equal sign.

    An array in scalar context evaluates to lengthof the array: $len = @stuff;

    (parenthesis) will put a scalar into list

    context: ($thing) = @stuff; # assigns $stuff[0]to $thing.

    Psudeo-function scalar can be used to toforce a list into a scalar. Example:

    scalar(@stuff);

  • 8/3/2019 Perl Intro 01

    19/29

    Quotes in Perl

    'Ordinary quotes'

    "Interpolated quotes - $vars exapanded\n", This ismy favorite..

    `execute a shell` command and return the resultas a string.

    my $var = " test ";

    print " $var\n",'$var\n

    ';

    Outputs:

    test

    $var\n

  • 8/3/2019 Perl Intro 01

    20/29

    Iterating over a hash

    #!/usr/bin/perl -w

    use strict;

    ...

    my $key, $value, %hash;

    ...

    while (($key, $value) = each %hash) {

    print $key $value "\n";

    }

  • 8/3/2019 Perl Intro 01

    21/29

    Pronouns in Perl

    $_ is the default variable Example:#!/usr/bin/perl -w

    use strict;

    my @array = ("a", "b", "c");

    # the following 2 loops are equivalent

    foreach my $element (@array) {

    print $element;}

    foreach (@array) {

    print;

    }

  • 8/3/2019 Perl Intro 01

    22/29

    Regular Expressions

    Much like SED

    if (/Bill Day/) # evaluate $_, true if it contains

    string. if ($var =~ /Bill Day/) # evalute $var for string.

    $var =~ s/Bill/William/; # substitue the 1st occuranceof Bill with William in $var.

    Lots of special characters: ., ?, *, +, (, ), [, ], | ^, \, {,},

    One of the most powerful features of Perl.

    Unfortunately beyond the scope of this talk.

  • 8/3/2019 Perl Intro 01

    23/29

    I/O in Perl

    open IN, "name"; # open name for reading.

    open HANDLE, "output; # create or truncatefile for output.

    open LOG, ">>logfile "; # append or create

    file for output. close HANDLE; # When done with file.

    All the POSIX C style stuff works.

  • 8/3/2019 Perl Intro 01

    24/29

    I/O in Perl Continued

    # (diamond operator) to read aline from the file.

    print HANDLE "string"; # prints to file. Note:no comma between HANDLE and string.

    with no handle reads each file given onthe command line, else if command lineblank STDIN. Just like you want yourstandard Unix utility to do.

  • 8/3/2019 Perl Intro 01

    25/29

    Errors and warnings

    die "meltdown in progress"; # message toSTDERR for fatal errors (exits program).

    warn "your shoe is untied."; # message toSTDERR for non-fatal warnings.

  • 8/3/2019 Perl Intro 01

    26/29

    Putting it all together#!/usr/bin/perl -w

    use strict;

    open ORIGINAL, "

  • 8/3/2019 Perl Intro 01

    27/29

    Where to get help

    In shell: perldoc perl

    In shell: perldoc perlre

    www.perl.com

    www.cpan.org

    www.activestate.com

    grand-rapids.pm.org

  • 8/3/2019 Perl Intro 01

    28/29

    Review

    Perl is the premier open source highperformance cross platform enterprise class

    object oriented language that holds togetherthe world wide web.

    There's more than one way to do it TMTOWTDI (Pronounced Tim-Toady)

    Perl makes Easy things easy, and hardthings possible.

    Questions?

  • 8/3/2019 Perl Intro 01

    29/29

    Exercises:

    1) Create a hash; write a program to loop through a hash

    and print all hash pairs.

    2) Write a program to read some numbers in from STDIN.stopping when the user types in 'quit', and print thetotal.

    3) Write a program to read in some words from thecommand line, replacing Matthew withMatt, and re-print the words back onto the command line.