for Web Applications 01 Introduction to Perl Alexandros Labrinidis - - PDF document

for web applications
SMART_READER_LITE
LIVE PREVIEW

for Web Applications 01 Introduction to Perl Alexandros Labrinidis - - PDF document

CS 1520 / Fall 2012 Programming Languages for Web Applications 01 Introduction to Perl Alexandros Labrinidis University of Pittsburgh What is Perl n P ractical E xtraction and R eporting L anguage n 1987 n Larry Wall n roots in


slide-1
SLIDE 1

1

CS 1520 / Fall 2012 Programming Languages for Web Applications

Alexandros Labrinidis University of Pittsburgh 01 – Introduction to Perl

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

2

What is Perl

n Practical Extraction and Reporting Language

n 1987 n Larry Wall n roots in unix applications (awk/sed) n http://history.perl.org

n Uses of Perl:

n EVERYWHERE :-) n Scripts for repeated tasks n Powerful regular expression matching n Text processing n Web programming

slide-2
SLIDE 2

2

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

3

How to run Perl programs (revised)

n

Use text editor (say pico) to write and save program, say hello.pl

n Option 1:

perl -w hello.pl

n

Next time:

perl - w hello.pl

n Option 2:

n Make sure first line of hello.pl is the following

#!/bin/perl -w

chmod u+x hello.pl ./hello.pl

n

Next time:

./hello.pl

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

4

Hello World

#!/bin/perl -w print (“Hello world!\n”);

n Observations:

n First line is needed to make program self-executable n -w flag is highly recommended: it prints out warnings n All statements in in semicolon ; n Strings are enclosed in double quotes “ (more on this later)

slide-3
SLIDE 3

3

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

5

Scalar Data: Numbers

n

Examples:Floating point literals

n 1.25 n 255.000 n 255.0 n 3.14159 n -6.5e24 n 1.2E-4

n

Examples: Integer literals

n 0 n 2001 n 1520 n -40 n 61298040283768 n 61_298_040_283_768 n

When we have “one of something”

n E.g., numbers, strings

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

6

Scalar Data: Numbers

n Examples: non-decimal integer

n 0377

is 377 octal, same as 255 decimal

n 0xff

is FF hex, same as 255 decimal

n 0b11111111

is in binary, same as 255 decimal

n 0x50_65_72_7C

slide-4
SLIDE 4

4

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

7

Numeric operators

n 2 + 3 # 2 plus 3, or 5 n 5.1 - 2.4 # 5.1 minus 2.4, or 2.7 n 3 * 12 # 3 times 12 = 36 n 14 / 2 # 14 divided by 2, or 7 n 10.2 / 0.3 # 10.2 divided by 0.3, or 34 n 10 / 3 # always floating-point divide, so 3.3333333... n Modulus operator:

n 10 % 3 # 10 module 3, or 1 n 10.5 % 3.2

# first converted to 10 % 3

n Exponent operator:

n 2 ** 3

# 2 to the 3rd, or 8

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

8

Scalar Data: Strings

n Strings are sequences of characters (like hello).

n Strings may contain any combination of any characters

n Two types:

n Single-quoted string literals n No variable substitution in string n Double-quoted string literals n Allow for variable substitution

slide-5
SLIDE 5

5

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

9

Single-quoted Strings

n 'fred'

# those four characters: f, r, e, and d

n 'barney' # those six characters n ''

# the null string (no characters)

n 'Don\'t let an apostrophe end this string prematurely!’ n 'the last character of this string is a backslash: \\’ n 'hello\n'

# hello followed by backslash followed by n

n 'hello

there' # hello, newline, there (11 characters total)

n ’\’\\'

# single quote followed by backslash

n

Note that the \n within a single-quoted string is not interpreted as a newline, but as the two characters backslash and n. Only when the backslash is followed by another backslash or a single quote does it have special meaning.

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

10

Double-quoted strings

n "barney"

# just the same as 'barney’

n "hello world\n"

# hello world, and a newline

n "The last character of this string is a quote mark: \"” n "coke\tsprite"

# coke, a tab, and sprite

slide-6
SLIDE 6

6

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

11

String operators

n Concatenation

n "hello" . "world" # same as "helloworld” n "hello" . ' ' . "world" # same as 'hello world’ n 'hello world' . ”\n" # same as "hello world\n”

n String repetition

n "fred" x 3

# is "fredfredfred”

n "barney" x (4+1) # is "barney" x 5, or

"barneybarneybarneybarneybarney”

n 5 x 4

# is really "5" x 4, which is "5555"

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

12

Scalar Variables

n A variable is a name for a container that holds one or

more values

n Unlike other languages, there is no variable definition/declaration

in Perl (unless you invoke “strict”)

n Example variable names:

n $a_very_long_variable_that_ends_in_1 n $a_very_long_variable_that_ends_in_2 n $Fred is different from $fred n $is_it_better_with_underscores n $orIsItBetterWithCaps

slide-7
SLIDE 7

7

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

13

Assignment

n $fred = 17;

# give $fred the value of 17

n $barney = 'hello';

# give $barney the five-character string 'hello’

n $barney = $fred + 3;

# give $barney the current value of $fred plus 3 (20)

n $barney = $barney * 2;

# $barney is now $barney multiplied by 2 (40)

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

14

Binary Assignment

n $fred = $fred + 5;

# without the binary assignment operator

n $fred += 5;

# with the binary assignment operator

n $barney = $barney * 3;

$barney *= 3;

n $str = $str . " "; # append a space to $str

$str .= " "; # same thing with assignment operator

slide-8
SLIDE 8

8

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

15

Print

print "hello world\n"; # say hello world, followed by a newline print "The answer is "; print 6 * 7; print ".\n";

  • OR:

print "The answer is ", 6 * 7, ".\n";

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

16

Scalar Variables into strings

n $meal = "brontosaurus steak"; n $barney = "fred ate a $meal";

# $barney is now "fred ate a brontosaurus steak”

n $barney = 'fred ate a ' . $meal;

# another way to write that

slide-9
SLIDE 9

9

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

17

Lists and Arrays in Perl

n Q: What is a List or Array? n A: a list is ordered scalar data n A: an array is a variable that holds a list n Example - list literals:

n (1, 2, 3)

#array of three values: 1, 2, and 3

n (“fred”, 4, 5)

#array of three values: “fred”, 4, and 5

n ($a, 42)

#two values: current value of $a and 42

n ($a+$b, $c+$d) #also two values n ()

#the empty list (no elements)

n (1 .. 5)

#same as (1, 2, 3, 4, 5)

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

18

More examples - arrays

n @a = (“rachel”, “phoebe”, “chandler”, “ross”,

“monica”, “joey”);

n Shortcut: n @a = qw(rachel phoebe chandler ross monica joey);

n qw stands for quote word: it creates a list from the

nonwhitespace parts within the parentheses

n @b = qw(mary 2 5 had a little 4 lamb 6); n Q: what will the following do?

print (“the answer is “,@a,”\n”);

slide-10
SLIDE 10

10

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

19

Arrays - Assignment

n @rachel = (1, 2, 3);

#the rachel array is a 3-element list literal

n @monica = @rachel;

#the rachel array is copied to the monica array

n @joey = 1;

# 1 is automatically converted to (1)

n @ross = qw(one two three);

# equivalent to @ross = (“one”, “two”, “three”);

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

20

Arrays - Assignment (RHS)

n @phoebe = qw(smelly cat);

#equivalent to @phoebe = (“smelly”, “cat”);

n @chandler = (“here”, “is”, @phoebe, 5, 6);

#chandler becomes (“here”, “is”, “smelly”, “cat”, 5, 6);

n @chandler = (42, @chandler);

#puts 42 in front of chandler

n @chandler = (@chandler, “last”);

#puts “last” at the end of chandler

slide-11
SLIDE 11

11

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

21

Arrays - Assignment (LHS)

n ($a, $b, $c) = (1, 2, 3)

#give value of 1 to $a, 2 to $b, 3 to $c

n ($a, $b) = ($b, $a)

#swap $a and $b

n ($d, @ross) = ($a, $b, $c)

#give $a to $d, and ($b, $c) to @ross

n ($f, @ross) = @ross;

#remove first element of @ross and give it to $f #this makes $f = $b, and @ross = ($c)

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

22

Scalar and List context

n Perl will do automatic “conversion” of an array,

depending on the context.

n List context: normal n Scalar context: when the array must be “squeezed”

into a scalar variable.

n In this case, the length of the array is returned!

n Examples:

n @barney = @fred;

# all of @fred is copied to @barney

n ($a) = @fred;

# $a gets the first element of @fred

n $a = @fred;

# $a gets the length of @fred

slide-12
SLIDE 12

12

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

23

Array Element Access

n Can access individual elements using the standard [ ]

notation

n Note: element index starts at 0

n Examples:

n @monica = (7, 8, 9); n $m = $monica[0];

# $m gets the 1st element of @monica

n $monica[0] = 15;

# now @monica = (15, 8, 9)

n $c = $monica[2];

# $c gets the last elem. of @monica

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

24

Control Structures

n Statement blocks n if/else statement

n unless

n while loop

n until loop

n do while loop

n do until loop

n for statement n foreach statement

slide-13
SLIDE 13

13

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

25

Statement blocks

{ first_statement; second_statement; third_statement; … last_statement; }

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

26

Control Structures: if/then

n if/else

n if ($a > 5) {

#do nothing } else { $a++; }

n unless

n Unless ($a>5) {

$a++; }

slide-14
SLIDE 14

14

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

27

If/else statement

if (some_expression) { true_statement1; true_statement2; … } else { false_statement1; false_statement2; … }

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

28

Comparison operators

n Distinction between numeric and string comparison

Numeric String

n Equal:

== eq

n Not equal:

!= ne

n Less than:

< lt

n More than:

> gt

n Less than or equal:

<= le

n More than or equal:

>= ge

slide-15
SLIDE 15

15

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

29

If/elsif/else statement

if (first_expression) { true_first_statement1; true_first_statement2; … } elsif (second_expression) { true_second_statement1; true_second_statement2; } else { all_false_statement1; all_false_statement2; … }

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

30

Control Structures: while

n while loop

n while ($a > 5) {

#do something }

n until

n until ($a <= 5) {

$a++; }

slide-16
SLIDE 16

16

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

31

Control Structures: do/while

n do/while loop

n do {

#do something } while ($a > 5);

n do/until loop

n do {

#do something } until ($a <= 5);

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

32

while and do/while loops

while (some_expression) { statement_1; statement_2; … } do { statement_1; statement_2; … } while (some_expression);

slide-17
SLIDE 17

17

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

33

while loop example

$stops = 0; do { $stops++; print “Next step is stop number $stop\n”; } while ($stops <5);

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

34

For statement

for (initial_expr; test_expr; re_initialize_expr) { statement_1; statement_2; … } initial_expr; while (test_exp) { statement_1; statement_2; … re_initialize_expr; }

slide-18
SLIDE 18

18

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

35

Foreach statement

foreach $I (@some_list) { statement_1; statement_2; … } @a = (1, 2, 3, 4, 5, 6); foreach $i (@a) { print $i,”\n”; }

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

36

Back to Arrays

array3.pl @phoebe = qw(smelly cat); @chandler = (“here”, “is”, @phoebe, 5, 6); foreach $a (@chandler) { print $a,”\n”; } $len = @chandler; for ($i=0; $i<$len; $i++) { print “element num $i is $chandler[$i]\n”; }

slide-19
SLIDE 19

19

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

37

Array slices

n @fred[0,1] is the same as ($fred[0], $fred[1]) n What do the following do?

n @fred[0, 1] = @fred[1, 0]; n @fred[0, 1, 2] = @fred[1, 1, 1]; n @fred[1, 2] = (9, 10); CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

38

Lists/Arrays/Slices (recap)

n Assignment (LHS vs RHS)

n @beniffer = (“ben affleck”, “jennifer lopez”); n $beniffer[1] = “jennifer gardner”; n ($fred, $barney) = (14, 25); n ($a, $b) = ($b, $a);

n Scalar vs List context

n $a = @beniffer; n print $a.”\n”; n print @bennifer.”\n”;

slide-20
SLIDE 20

20

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

39

Lists/Arrays/Slices: Push/Pop

n Push (to right end of array)

n Adds an element to end of list n @list = (2, 4, 6); n push @list, 5;

# @list now (2, 4, 6, 5);

n Push @list, (3, 10);

# @list now (2, 4, 6, 5, 3, 10);

n Pop (from right end of array)

n Removes the last element of a list n $p = pop @list;

# $p becomes 10

n

# @list now (2, 4, 6, 5, 3);

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

40

Lists/Arrays/Slices: Shift/Unshift

n Unshift (to left end of array)

n Adds an element to the beginning of list n @list = (2, 4, 6); n unshift (@list, 7);

# @list now (7, 2, 4, 6);

n unshift (@list, 1, 12);

# @list now (1, 12, 7, 2, 4, 6);

n Shift (from left end of array)

n Removes the first element of a list n $p = shift @list;

# $p becomes 1

n

# @list now (12, 7, 2, 4, 6);

slide-21
SLIDE 21

21

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

41

Lists/Arrays/Slices: Sort/Reverse

n Sort

n sorts elements of an array n Example: n @x = qw(small medium large); n @y = sort (@x);

# @x stays the same

n

# @y is (“large”, “medium”, “small”)

n Reverse

n Reverses current order (i.e., NOT the reverse sort order) n @a = (10, 5, 12, 45); n @b = reverse @a;

# @a stays the same

n

# @b is (45, 12, 5, 10)

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

42

Hashes

n Arrays are nice, index is always numeric n Q: Would it not be nice to access arrays using strings? n A: Yes. n A: using Hashes! n %class is a hash n Initialization:

n $class{“CS1520”} = “SENSQ 5129”; n %class = (“CS1520” => “SENSQ 5129”,

“CS1555” => “SENSQ 5129”);

n %class = (“CS1520”, “SENSQ 5129”, “CS1555”, “SENSQ

5129”);

slide-22
SLIDE 22

22

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

43

Hash Functions

n keys(%hashname)

n return the list of current keys n $fred{“a”} = “b”; n $fred{“c”} = “d”; n $fred(15) = 143; n @list = keys(%fred);

# @list = (“a”, “c”, 15);

n $n = keys(%fred);

# $n = 3;

n foreach $k (keys (%fred)) {

print “we have $fred{$k} at key $k\n”; }

n values(%hashname)

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

44

Hash functions (cont)

n each (%hashname)

n Iterate over all elements of hash hashname n $lastname{“Alex”} = “Labrinidis”;

$lastname{“Panos”} = “Chrysanthis”; $lastname{“John”} = “Ramirez”; while ( ($first, $last) = each (%lastname) ) { print “The last name of $first is $last\n”; }

n delete

n delete $lastname{“Panos”};

slide-23
SLIDE 23

23

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

45

Regular Expressions (intro)

n grep abc somefile > results n while (<>) {

if (/abc/) { print $_; } }

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

46

Input/Output

n Output:

n print - simple n printf - formatted version

n Input:

n standard input is accessed via <STDIN> n will return 0 if no more input n <> form is more general; can read from files n $_ to access line within loop n while (<STDIN>) {

print $_; }

slide-24
SLIDE 24

24

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

47

Input (cont)

n Scalar versus List context:

n $a = <STDIN>;

# reads next line of input

n @b = <STDIN>;

# reads all lines at once

n Useful string functions:

n length(str)

# returns length of string

n uc ()

# converts to upper case

n lc()

# converts to lower case

n chomp(str)

# removes trailing \n

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

48

Variables: Scalar/Arrays/Hashes

n Scalar:

n $a n $asdflasdhjfgakhjsdf n No type defined

n Arrays:

n @b n $b[1] = second element of array b n No size defined

n Hashes:

n %c n $c{“alex”} = element of hash c whose key is “alex”

slide-25
SLIDE 25

25

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

49

User-defined functions

n sub myfunction {

statement_1; statement_2; … }

n sub say_hello {

print “Hello world\n”; }

n sub say_what {

print “Hello $what\n”; # $what is global var }

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

50

Invoking user-defined functions

n Very simple:

n say_hello();

n Can also be part of an expression:

n $a = $b + say_hello();

n Q: How to return values? n A: using the return command

slide-26
SLIDE 26

26

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

51

How to pass arguments?

n @_ is a special array that holds all arguments to current

function

n Two standard ways to use it:

n $_[0] is the first argument, $_[1] is the second argument, … n ($a, $b) = @_;

#assigns first arg to $a and second arg to $b

n Examples:

n addtwo.pl CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

52

Lexical Scope

n Global variables

n Variables outside the function are accessible within the function n Scope: global

n Private variables in functions

n my ($sum); n Scope: only valid while inside the current statement block

(i.e., function)

n Semi-private variables in functions

n local ($sum) n Scope: valid until function terminates

(i.e., even if another function was called from within)

slide-27
SLIDE 27

27

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

53

Examples

n

spoof.pl

n

add_any.pl: sub add { my ($sum); # private variable $sum = 0; # initialize foreach $param (@_) { # go over all args $sum += $param; # update sum } return $sum; # return total }

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

54

use strict;

n You can enforce “declaration” of variables by putting

use strict; at the beginning of your program

n Variables that are not “declared” will cause an error

n Note: we are still only declaring variables by name. No type

information (integer/string/etc) is given!

n Declare variables using my:

n my ($a, $fred, $wilma);

slide-28
SLIDE 28

28

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

55

Command-line arguments

n Array @ARGV holds all arguments n Example:

n argv.pl

n By default, <> operator will open all files that are in

ARGV and read through them one at a time (line by line)

n Better way to open files:

n open() function CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

56

Input/Output

n Output:

n print - simple n printf - formatted version

n Input:

n standard input is accessed via <STDIN> n will return 0 if no more input n <> form is more general; can read from files n $_ to access line within loop n while (<STDIN>) {

print $_; }

slide-29
SLIDE 29

29

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

57

Input (cont)

n Scalar versus List context:

n $a = <STDIN>;

# reads next line of input

n @b = <STDIN>;

# reads all lines at once

n Useful string functions:

n length(str)

# returns length of string

n uc ()

# converts to upper case

n lc()

# converts to lower case

n chomp(str)

# removes trailing \n

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

58

File I/O

n Filehandles: name of an I/O connection

n STDIN: standard input, from keyboard n STDOUT: standard output, your screen (where print goes)

n open (FILE, “somename”);

n FILE is the new filehandle n Somename is the external filename

n close (FILE);

slide-30
SLIDE 30

30

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

59

Open examples

n Input

n open (IN, “myfile.txt”);

n Output

n open (OUT, “>myfile2.txt”);

n Append

n open (APP, “>>myfile3.txt”); CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

60

Testing for Success

n Open returns true if was successful, false otherwise n MUST ALWAYS TEST RETURN VALUE! n if (open (IN, “myfile”)) {

print “success\n”; } else { print “failure\n”; }

slide-31
SLIDE 31

31

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

61

A simpler way

n if (open (FILE, “myfile.txt”)) {

#success } else { #failure print “Sorry, I could not find myfile.txt\n”; }

n Perl’s shortcut: die()

n Will print an error message and exit

n open (FILE, “myfile.txt”) || die (“Sorry, I could not find

myfile.txt”);

CS 1520 / Fall 2012 Alexandros Labrinidis, Univ. of Pittsburgh

62

File tests

n Test properties of files:

n -s filename tests if file exists and has non-zero size

n Usage:

if (-s $filename) { #file exists } else { # files does not exist }