Perl Practical Extraction and Report Language. 2 Objectives Introduction Basic features Variables...

Post on 17-Jan-2016

214 views 3 download

Transcript of Perl Practical Extraction and Report Language. 2 Objectives Introduction Basic features Variables...

Perl

Practical Extraction and Report Language

2

Objectives

Introduction Basic features Variables Operators and functions Control structures Input and output

3

Perl is a script language Elements of csh, sh, awk and C Used for:

Text manipulation CGI scripting System administration

Written and maintained by Larry Wall Websites

www.perl.com www.perl.org www.perldoc.com www.perlfoundation.org www.cpan.org

Introduction to Perl

4

Example:

#! /usr/bin/perl

# example of perl script

print “hello world\n”;

print(“hello world\n”);

printf(“hello world\n”);

printf(“%s\n”, “hello world”);

Introduction to Perl

5

Variables

Scalar Single valued

Array Indexed collection of values

Hash Collection of key, value pairs

6

Scalar Variables

string$word = “test”;

print “here it is: $word \n”;

quotes around string optional, if clear$word = test;

print “here it is $word \n”;

7

Scalar Variables

integer

$i = 2;print $i;print “$i\n”;

$j = 2 * $i + 4;

printf(“Result %d \n”, $j);print “Result $j \n”;

8

Scalar Variables

floating point

$f = 1.234;

$g = 2 * $f + 4;

printf("Result %f\n", $g);

print "Result $g\n";

9

Reading Input

from Standard input

print("enter a number: ");

$number = <>;

chop($number);

print("here it is: $number \n");

10

Array Variables

Array holds list:

("one", "two", "three")

(1, 4, 5, 7, 8, 0)

(1.2, 4.3, 6.5)

(“one”, 2, 3.14159)

($word, $i, $f)

11

Array Variables

array variable starts with @

@list=("one", "two", "three");

print “@list \n”;

array element starts with $

print("here it is: $list[0]\n");

print("here it is: $list[1]\n");

print("here it is: $list[2]\n");

12

Array Variables

array slice

@list=("one", "two", "three”, 4);@a = @list[1..3];@b = @list[2,0];

or:

@c = ("one", "two", "three”, 4)[2,0]

13

Array Variables

assignment

($first, $second) = (“one”, “two”);

@list = ($first, $second);

($o1, $o2) = @list;

array size

$size = @array; highest array index

$#array

14

Array Variables

example: swap two variables

$temp = $first;

$first = $second;

$second = $temp

better:($first, $second) = ($second, $first);

15

Array functions

to remove element from front shift @array;

to remove element from back pop @array;

to reverse elements reverse @array;

to sort elements sort @array;

16

Variables

Hash: associative array

%animals = ("cat“ => 10,

"dog“ => 12,

"fish“ => 23);

print("1: $animals{'cat'}\n");

print("2: $animals{'dog'}\n");

print("3: $animals{'fish'}\n");

17

Hash variable operation

%animals = ("cat“ => 10,

"dog“ => 12,

"fish“ => 23);

%index = reverse %animals;

print("1: $index{‘10'}\n");

print("2: $index{‘12'}\n");

print("3: $index{‘23'}\n");

18

Hash variable operation

%animals = ("cat“ => 10,

"dog“ => 12,

"fish“ => 23);

@names = keys %animals;

@numbers = values %animals;

19

Special Variables

Default parameter: $_

Used by many operations when no parameters are given

Example:$_ = “hello world\n”;

print;

20

Command line arguments

$ARGV[0], $ARGV[1], …

print("$ARGV[0], $ARGV[1]\n");

With a loop:$size = @ARGV;

for ($i = 0; $i < $size; $i++)

{

print("$ARGV[$i]\n");

}

21

Environment variables

%ENV hash

examples:

print $ENV{HOME};

print $ENV{PATH};

$ENV{EDITOR} = “emacs”;

22

Operators numeric: + - * / % ++ -- boolean: && || ! and or not & | ^ string:

. x

examples:

$a = “foo” . “bar”;

$b = “number “ . 1;

$c = “1” . “2”;

$d = “ba” . (“na”x4);

$e = 1 x 3;

23

String functions

remove last character: chop

remove last character, if it is “\n”: chomp

$a = “foobar\n”;

print chop(a);

print chomp(a);

24

String function: split

split string into words needs word separator example:

$test = “one two three”;

@list = split “ “, $test;

print “@list\n”;

25

String function: split

split with no parameters will split $_ on whitespace

example:

$_ = “one two three”;

print split;

26

String function: split

word separator examples: split on string

“:”

split on regular expression /e.e/ /[abc]/

27

String function: join

opposite of split:

@list = (“one”, “two”, “three”);

$text = join “?”, @list;

28

String function: substr manipulate substring

$string="the glistening trophies"; print substr($string, 15); # trophies print substr($string, -3); # ies print substr($string, -18, 9); # listening print substr($string, 4, 4); # glis

substr($string, 7, 4, "tter"); # Returns "sten" print $string; # the glittering trophies

substr($string, 7, 4) ="tter"; # Functions as lvalue

29

Control Structures

sequence: run until end of file exit and die

conditional: if-then-else, unless

loops: for while

functions

30

Sequence

all statements are terminated with semicolon to end execution

exit;

to end with error message die(“it was the food”);

to just print a warning (without exiting) warn(“it is too warm in here”);

31

Conditional

if

if ( $i > 10 ) {

print “yes\n”;

} else {

print “no\n”;

}

32

Conditional

unless

unless ( $i > 10 ) {

print “no\n”;

} else

print “yes\n”;

}

33

Conditional

one liners:

print “no\n” unless ( $i > 10 );

print “yes\n” if ( $i > 10 );

die(“unhappy”) unless ( $happy > 0);

34

Loops

C-like for loop:

for ($i=0; $i<5; $i++) {print “Counter is $i\n”;

}

simplified:

for $i (0..4) {print “Counter is $i\n”;

}

35

Loops

for arrays:

@array = (“one”, “two”, “three”);

foreach (@array) {

print “value is $_ \n”;

}

36

Loops

while:

$i=10;

while ($i > 5) {

print “value is $i \n”;

$i--;

}

37

Loops

special keywords within while:

next skip to next iteration

last end loop

redo rerun iteration

38

Pattern matching

Perl supports regular expressions basic and extended enclosed in forward slash “/”

match operator =~ return boolean true or false

$sea = “water sand jaws swimmers”;print “Shark Alert !” if $sea =~ /jaws/;

39

Pattern matching

special characters:\w - word \W - non word\s - space \S - non space\d - digit \D - non digit\b - word boundary

40

Pattern matching

pattern may include parenthesis () identifies matched junks as $1, $2, $3

$sea = “water sand jaws swimmers”;print “Shark Alert !” if $sea =~ /(j??s)/;print $1;

41

Pattern substitution

$test = “he said she said”;$test =~ s/said/did/;

42

Sub-functions

example:

sub greeting {

print “hello world\n”;

}

greeting();

43

Sub-functions

parameters are passed via @_ array:

sub action {($one, $two, $three) = @_;warn “too few parameters”

unless $one && $two && $three;print “The $one $two on the $three\n”;

} …

action(“cat”, “sat”, “hat”);

44

Sub-functions

return results via return:

sub action {($one $two $three) = @_;warn “too few parameters”

unless $one && $two && $three;return “The $one $two on the $three\n”;

} …

print action(“cat”, “sat”, “hat”);

45

Sub-functions

local variables: visible only with scope of sub-function

sub getwords {

my pat = $_[0];

my ($line, @subwords);

$line = <>;

chop($line);

@subwords = split /$pat/, $line;

return @subwords;

}

46

Reading Input

from Standard input

print("enter a number: ");

$number = <STDIN>;

print("here it is: $number");

47

Reading Input

from Standard input

$i = 0;

while ($line = <STDIN>) {

print $line;

$i++;

}

print(“line count: $i \n");

48

File I/O

based on file handle predefined file handles

STDIN

STDOUT

STDERR

print STDERR “…oohh, something went wrong !\n”;

49

File I/O

to create new file handle open file open filehandle filename;

filename can be: “file” “<file” “>file” “>>file”

“ls|” “|wc”

50

Reading from a File

if (!open(FILE, "$ARGV[0]")) { print "cannot open: $ARGV[0]\n“ ;}while ($line = <FILE>) { print "$line“ ;}

51

Reading complete File

die “horribly” unless open FILE “t.txt”;@all = <FILE>;$linecount = @all;print “line count: $linecount”;

52

Writing to a File

die "cannot open: $ARGV[0]” unless open FILE, “>$ARGV[0]“

@array = (“one”, “two”, “three”);foreach (@array) { print FILE “$_ \n”;}

53

Running system commands

via backquotes ` `$result = `ls | wc –w`

via system function$result = system(“ls | wc –w”);

via file I/Oopen FILE, “ls | wc –w|”;$result = <FILE>;

54

Running system commands

#!/usr/local/bin/perl# convert series of files from DOS to Unix format

if ($#ARGV < 0) { print "usage: fconvert files\n"; exit;}foreach (@ARGV) { $cmd = "dos2unix $_ $_.unix"; print "$cmd\n"; if(system($cmd)) { print "dos2unix failed\n"; }}

55

Html via Perl#!/usr/local/bin/perl# create n html files linked together in slide showif ($#ARGV != 1) { print "usage: htmlslides base num\n"; exit;}$base = $ARGV[0];$num = $ARGV[1];for ($i=1; $i <= $num; $i++) { open(HTML, ">$base$i.html"); if($i==$num) { $next = 1; } else { $next = $i+1; } print HTML "<html>\n<head>\n<title>$base$i”; print HTML “</title>\n</head>\n<body>\n"; print HTML "<a href=\"$base$next.html\">”; print HTML “<img src=\"$base$i.jpg\"></a>\n"; print HTML "</body>\n</html>\n"; close(HTML);}

56

Perl modules

contain large amounts of reusable code CPAN: Comprehensive Perl Archive Network

networking web related cgi processing database access spam protection …

57

Web & CGI

HTML may include forms to invoke server side functions CGI (Common Gateway Interface) is a protocol

governing how browsers and servers communicate Scripts that send or receive information need to follow

the CGI protocol Perl is the most commonly used language for CGI

programming Perl scripts are written to get, process, and return

information through Web pages

58

Html via Perl

#! /usr/local/bin/perl

print “Content-type: text/html\n\n”;

print “<html><head><title>Hello World</title>”;

print “</head><body>\n”;

print “<h2>Test Website</h2>";

print “</body></html>”;

59

Html via Perl

CGI module:

use CGI qw(:standard);

print(header);

print(start_html("Hello World"));

print h2("Test Website");

print(end_html);

60

Web Page

<html><head><title>COP 3344</title></head><body><h1>User Inquiry</h1><form method=get action=/cgi-bin/example.cgi>Enter your name: <input type="text" size=20 name="userid"><br><input type="submit" value="Submit"></form></body></html>

61

Interactive Web Page

62

Perl script: example.cgi

#! /usr/local/bin/perl# example perl scriptuse CGI qw(:standard);print(header);print(start_html("Anser Page"));print h2("Answer Page");print("Welcome: ", param('userid'));print(end_html);

63

Interactive Web Page

64

Chapter Summary

Perl is a powerful scripting language Perl scripts are used to create web pages CGI is a protocol or set of rules governing how

browsers and servers communicate