Perl - PowerPoint PPT Presentation

1 / 106
About This Presentation
Title:

Perl

Description:

x = 2 # _at_fred = (3,4,5,6,7) shift( ) and pop( ) returns undef on an ... pokemon = ('pk','pikachu','tp','togepi','gy','gyrados'); Elements: (key, scalar) pair. ... – PowerPoint PPT presentation

Number of Views:104
Avg rating:3.0/5.0
Slides: 107
Provided by: jack86
Category:
Tags: perl | pokemon

less

Transcript and Presenter's Notes

Title: Perl


1
Perl
  • Practical Extraction and Report Language
  • Not designed for the Web
  • Designed by Larry Wall in 1986 to create reports
  • Drew upon useful features in other programming
    languages
  • (Pathologically Eclectic Rubbish Lister)

2
Perl overview
  • Originally called PEARL, but a conflict with an
    existing graphics language resulted in the
    shortening of the name
  • Language includes pattern matching, file
    handling, and scalar data
  • It has syntax patterned after C and was
    originally designed to operate as a shell script
  • Its power is that it views programs and files as
    data
  • It has proven to be an effective language for
    interacting with Web pages

3
Perl structure
  • ? Variables in Perl are either integers or
    strings and begin with the
  • symbol .
  • ? A simple Perl program consists of a series of
    print statements.
  • ? It has the usual sequence of control structures
    such as for, while,
  • and until loops and if conditional.

4
Perl is good for
  • Quick scripts, complex scripts
  • Parsing restructuring data files
  • CGI-BIN scripts
  • High-level programming
  • Networking libraries
  • Graphics libraries
  • Database interface libraries

5
Bad for ..
  • Compute-intensive applications (use C)
  • Hardware interfacing (device drivers)

6
Perl structure
  • Comment lines begin with
  • First line should look like !/bin/perl
  • File Naming Scheme
  • filename.pl (programs)
  • filename.pm (modules)
  • filename.ph (old Perl 4 header file)
  • Example prog print Hello, World!\n

7
Perl structure
Statements must end with semicolon. a
0 Should call exit() function when
finished. Exit value of zero means
success exit (0) successful Exit
value non-zero means failure exit (2)
failure
8
Perl structure
  • ? Perl shares an ability to process regular
    expressions like several other process languages
  • Example use
  • ENV'USER' ? mvz
  • will be true if login name mvz is the string
    ENV'USER' (i.e., is the
  • user running this program).
  • This shows how Perl can interact with the system
    environment

9
Perl Example script
  • if (food eq "spinach")
  • print "You ate spinach, so you get dessert!"
  • elsif (food eq "broccoli")
  • print "Broccoli's OK. Maybe you'll get
    dessert."
  • else
  • print "No spinach, no dessert!"

10
Perl The learning process
  • Access to Perl Interpreter on a server
  • Can download and install for free
  • Perl on UNIX server (needed to learn basic UNIX
    commands).
  • Basic Text Editor (e.g., Vi, Vim, Emacs, etc.)

11
Perl
12
Perl
13
Perl
14
Data Types
  • Integer
  • 25 750000 1000000000
  • Nondecimal Integer
  • 0567 (Octal 567)
  • 0xff (Hex FF)
  • 0b10111011 (Binary 10111011)

15
Data Types
  • Perl 5.6 (and later) allows underscores for
    readability
  • 0b1011_1011
  • 0x0000_FFFF

16
Data Types
  • Floating Point
  • 1.25 50.0 6.02e23 -1.6E-8
  • String
  • hi there hi there, name qq(tin can)
  • print Text Utility, version ver\n

17
Perl
18
Data Types
  • Boolean
  • 0 0.0 represents False
  • all other values represents True

19
Data Types
  • Scalar
  • num 14
  • fullname Cass A. Nova
  • Variable Names are Case Sensitive
  • Underlines Allowed
  • Program_Version 1.0

20
Perl
21
Perl
22
Perl
23
Perl
24
Basic I/O Input from STDIN
Evaluating this operator in a scalar context
gives you the next line of input, or undef, if
there are no more lines. a ltSTDINgt
read the next line
25
Basic I/O Input from STDIN
? Evaluating this operator in an array context
gives you all of the remaining lines as a
list. ? One line per element. _at_a ltSTDINgt
read the next line
26
Basic I/O Input from STDIN
? To read a scalar value for ltSTDINgt and use
value as the controlling expression of a
loop while (ltSTDINgt) like while
(_ ltSTDINgt) chomp
like chomp (_ ) process _ here

27
Input from Diamond Operator ltgt
Unlike ltSTDINgt, lt gt gets data from file(s)
specified on the command line that invoked the
Perl program. E.g., if Perl file is called foo,
consisting of !/usr/bin/perl -w while (ltgt)
print _
28
Input from Diamond Operator ltgt
And you invoke foo with foo file1 file2
file3 lt gt will read each line of file1 followed
by each line of file2 followed by each line
of file3. Acts like UNIXs cat(enate) command
29
Input from Diamond Operator ltgt
? lt gt does not look at command line arguments. ?
Uses the _at_ARGV array ? ARGV returns the number
of arguments ? Set by Perl to contain the list of
command-line arguments Example set _at_ARGV
in-program. _at_ARGV (passwd1,passwd2,passwd3
) while (ltgt) process files passwd? print
This line is _
30
ltgt example
? print lines that are not blank lines while
(ltgt) chop if (_ ne ) print
_ \n Note run diamond2.pl under tan
31
Output to STDOUT
? print or printf ? Parenthesis optional, needed
for clarification readability. E.g., print
(23),hello wrong! Prints 5, ignores
hello print ((23),hello) right, prints
5hello print 23,hello also right, prints
5hello
32
Output to STDOUT
? printf for formatted output (from
C) E.g., format width printf 15s 5d
10.2f\n, s, n, r string integer floatin
g point
33
Built-in Perl Operators chop
  • Scalar Context
  • Chop off and return the last character of a
    string
  • s string c chop(s)
  • s ? strin c ? g
  • Array Context
  • Chop off the last character of every string in
    the array, but return the last character of the
    last element of the array.
  • _at_s (s1, s2, s3)
  • chop(_at_s) ? _at_s (s, s, s)

34
chomp
  • Scalar Context
  • Remove and return the last character of a string,
    if and only if it equals the current record
    separator value (\n).
  • s string\n c chomp(s)
  • s ? string c ? \n
  • Array Context
  • Remove the last character of every string in an
    array only if it is the current record separator
    value.
  • _at_s (hello\n, world)
  • chomp(_at_s) ? _at_s (hello, world)

35
Perl
36
Perl
37
Perl
38
Examples with strings..
fred hi barney a test of .fred
yields a test of fred barney2 a test
of \fred same result as above
39
Examples with strings..
fred pay fredday wrong! barney
Its fredday not Its payday, but Its
wrong! barney Its fredday now,
barney Its payday barney2 Its fred
. day another way to do it, and another
barney3 Its.fred.day
40
Arrays
  • List (one-dimensional array)
  • _at_memory (16, 32, 48, 64)
  • _at_people (Alice, Alex, Albert)
  • First element numbered 0 (can be changed)
  • Single elements are scalar
  • names0 Fred
  • Slices are ranges of elements
  • _at_guys _at_people1..3
  • How big is my list?
  • print Number of people people\n

41
Examples of Arrays
(1, 2, 3) array of three values (fred,4.5)
two values Elements can be expressions (a,
17) two values, current value of a, and
17 (bc, ad) two values Empty array ( )
42
Examples of Arrays
Ranges allowed (1..3) same as (1, 2,
3) (2..4,10,12) (2,3,4,10,12) (a..b)
depends on those values Float ranges (1.2..5.2)
(1.2,2.2,3.2,4.2,5.2) (1.2..6.1)
(1.2,2.2,3.2,4.2,5.2)
43
Examples of Array Variables
_at_fred (1,2,3) fred array gets 3
elements _at_barney _at_fred that is copied to
barney Array variable name may appear in array
literal list _at_fred (one,two) _at_barney
(4,5,_at_fred,6,7) (4,5,one,two,6,7) _at_barne
y (8, _at_barney) puts 8 in front of
_at_barney
44
Examples of Array Variables
When array variable is assigned a
scalar variable, number assigned is length of
array _at_fred (4,5,6) initialize _at_fred a
_at_fred a gets 3, current length of
_at_fred
45
Examples Element Access
_at_fred (7,8,9) b fred0 b
7 fred0 5 _at_fred (5,8,9) fred2
increment 3rd element of
_at_fred (fred0,fred1) (fred1,fred0)
swap first two
46
Examples Element Access
Slice access list of elements _at_fred0,1
same as (fred0,fred1) _at_fred0,1
_at_fred1,0 swap _at_fred0,1,2 _at_fred1,1,1
make all 3 elements same as 2nd
element _at_fred1,2 (9,10) change last 2
values 9 and 10 Note _at_ instead of
47
Examples Index Expressions
Index can be any expression that returns a
number, e.g., _at_fred (7,8,9) a 2 b
freda fred2 9 c freda-2 c
fred0 7
48
Examples Out-of-bounds access
undef value that represents something that is
not defined. _at_fred (1,2,3) fredi for
0 lt i gt 2 yields undef value e.g., barney
fred7 barney is now undef
49
Examples Out-of-bounds assignment
Assigning a value beyond the end of the current
array automatically extends the array, giving
undef to all intermediate values, if any. _at_fred
(1,2,3) fred3 hi _at_fred is now
(1,2,3,hi) fred6 ho _at_fred
(1,2,3,hi,undef,undef,ho))
50
Examples Array as a stack
Top of stack right-hand side of
array. push(_at_mylist, newvalue) _at_mylist
(_at_mylist, newvalue) oldvalue pop(_at_mylist)
removes last element of _at_mylist
51
Examples push
Push also accepts a list of values to be
pushed. _at_mylist(1,2,3) push(_at_mylist,4,5,6)
_at_mylist (1,2,3,4,5,6)
52
Examples shift( ) unshift( )
push( ), pop( ) operates on right side of
list shift( ), unshift( ) acts on left
side. unshift(_at_fred,a) _at_fred
(a,_at_fred) unshift(_at_fred,a,b,c) _at_fred
(a,b,c,_at_fred)
53
Examples shift( ) unshift( )
_at_fred (5,6,7) unshift(_at_fred,2,3,4) push()
from left end _at_fred (2,3,4,5,6,7) x
shift(_at_fred) pop() from left end x 2
_at_fred (3,4,5,6,7) shift( ) and pop( ) returns
undef on an empty array.
54
reverse( )
  • Reverses the order of the elements.
  • _at_a (7,8,9)
  • _at_b reverse(_at_a) _at_b (9,8,7)
  • _at_b reverse(7,8,9) same thing

55
sort( )
  • Sorts arguments as ascending ASCII order of
    single strings.
  • Original list is unaltered.
  • _at_x sort(small,medium,large)
  • _at_x (large,medium, small)
  • _at_y (1,2,4,8,16,32,64)
  • _at_z sort(_at_y)
  • _at_z (1,16,2,32,64,8)
  • numbers are interpreted as string values

56
Variable interpolation of arrays
  • Like scalars, array values may be interpolated
    into a
  • double-quoted string.
  • _at_fred (hello,Dolly)
  • y 2
  • x This is fred1s place
  • This is Dollys place
  • x This is fredy-1s place
  • This is Dollys place

57
Variable interpolation of arrays
  • When and how to escape ?
  • _at_fred (hello,dolly)
  • fred right
  • want to say this is right1
  • x This is fred1
  • wrong! gives This is dolly must \
  • x This is fred\1 or ..

58
Variable interpolation of arrays
  • When and how to escape ?
  • x This is fred.1
  • x This is fred1

59
Scalar vs Array Context
  • Perl variables act differently depending on the
    context theyre evaluated in.
  • Example _at_days (Mon, Tue, Fri)
  • _at_days evaluated in an array context returns the
    contents of the _at_days array
  • Mon Tue Fri
  • _at_days evaluated in a scalar context returns the
    number of elements in the _at_days array
  • n _at_days ? n 3

60
Scalar vs Array Context
  • Many perl operators and functions behave
    differently depending on context.
  • Note that if a function expects a scalar context
    and you pass in an array, the array will be
    evaluated in a scalar context

61
Associative Arrays (AA)
Hash arrays index values are not small
non-negative integers. Index values arbitrary
scalars, called keys. AA elements no particular
order. Analogy consider AA as a deck of filing
cards. - top half of each card is the key -
bottom half is the value - each time a value is
inserted, a new card is created.
62
Associative Arrays (AA)
AA variable name is a percent () sign followed
by a letter, followed by 0 letters, digits,
and underscores. pokemon (pk,pikachu,tp,
togepi,gy,gyrados) Elements (key,
scalar) pair. Reference pokemonkey where
keypk for example. Notice symbols and braces
used.
63
Associative Arrays (AA)
Adding new elements pokemonpc
pichu pokemon234.5 45.6 creates key
234.5, value 45.6 Watch your symbols! print
pokemonpc prints pichu print
pokemon234.5 3 ? 48.6
64
Literal Representation of an AA
Need to access AA as a whole, e.g., to initialize
or copy an entire AA ? Unfold AA into an array
list E.g., _at_pokemon_list pokemon
unfold pokemon _at_pokemon_list
(pk,pikachu,tp,togepi,gy,gyrados)

65
Literal Representation of an AA
E.g., _at_pokemon_list pokemon _at_pokemon_list
(pk,pikachu,tp,togepi,gy,gyrados)
yugioh _at_pokemon_list create yugioh like
pokemon. Auto-fold yugioh pokemon
faster way to do the same thing anime
(pk,pikachu,tp,togepi,gy,gyrados)
create anime from literal values
66
The keys( ) operator
keys(array_name) returns A list of all current
keys of array_name, e.g., lastname ( )
force lastname empty lastnamedon
corleone create new entries lastnametom
hagen _at_last keys(lastname) contains
either (don,tom) or reverse of that
67
The values( ) operator
values(array_name) returns A list of all
current values of array_name, e.g., lastname
( ) force lastname
empty lastnamedon corleone create
new lastnametom hagen entries _at_last
values(lastname) contains either
(corleone,hagen) or reverse of that
68
Variable Types
  • Hash (associative array)
  • var name gt paul, age gt 33
  • Single elements are scalar
  • print varname varage
  • How many elements are in my hash?
  • _at_allkeys keys(var)
  • num allkeys

69
The each( ) operator
Examine every element of AA? Use keys() operator
to extract each key to index into the associative
array (Try it.) Or use the each() operator,
i.e., each(arrayname) while ((first,last)
each(lastname)) print Last name of first
is last\n
70
The delete( ) operator
Delete a (key, value) pair anime
(pk,pikachu,tp,togepi,gy,gyrados) del
ete anime(tp) now anime
(pk,pikachu,gy,gyrados)
71
Operators
  • Math
  • The usual suspects - /
  • total subtotal (1 tax / 100.0)
  • Exponentiation
  • cube value 3
  • cuberoot value (1.0/3)
  • Bit-level Operations
  • left-shiftltlt val bits ltlt 1
  • right-shiftgtgt val bits gtgt 8

72
Operators
  • Assignments
  • As usual - / ltlt gtgt
  • value 5
  • longword ltlt 16
  • Increment
  • counter or counter
  • Decrement --
  • num_tries-- or --num_tries

73
Perl
74
Operators
  • Boolean (against bits in each byte)
  • Usual operators
  • Exclusive-or
  • Bitwise Negation
  • picture backgnd mask image
  • Boolean Assignment
  • picture mask

75
Operators
  • Logical (expressions)
  • And operator
  • Or operator
  • ! Not operator
  • AND And, low precedence
  • OR Or, low precedence
  • NOT Not, low precedence
  • XOR Exclusive or, low precedence

76
Operators
  • Short Circuit Operators
  • expr1 expr2
  • expr1 is evaluated.
  • expr2 is only evaluated if expr1 was true.
  • expr1 expr2
  • expr1 is evaluated.
  • expr2 is only evaluated if expr1 was false.
  • Examples
  • open () die couldnt open file
  • debug print users name is name\n

77
Operators
  • Modulo
  • a 123 10 (a is 3)
  • Multiplier x
  • print ride on the , choo-x2, train(prints
    ride on the choo-choo-train)
  • stars x 80
  • Assignment x

78
Operators
  • String Concatenation . .
  • name Uncle . space . Sam
  • cost 34.99
  • price Hope Diamond, now only \
  • price . cost

79
Conditionals
  • numeric string
  • Equal eq
  • Less/Greater Than lt gt lt gt
  • Less/Greater or equal lt gt le ge
  • Zero and empty-string means False
  • All other values equate to True

80
Examples
  • a 3
  • b (a 4) a, b are both 7 now
  • Unfortunately, order of evaluation of operands is
    unspecified
  • ? some expressions are undetermined
  • a 3
  • b (a2) (a-2) BAD CODE b could be
    15 or 3!

81
Autoincrement rule
For prefix d 17 e d d, e are
both 18 (prefix op) For postfix result of
expression is value of variable before it is
incremented c 17 d c d 17,
but c 18
82
Autoincrement rule
Unlike C, autoincrement works on floats! c
4.2 c makes it 5.2
83
Conditionals
  • numeric string
  • Comparison ltgt cmp
  • Results in a value of -1, 0, or 1
  • Logical Not !
  • if (! done) print keep going
  • Grouping ( )

84
Operator Precedence (low-to-high)
right - etc. right ?
nonassoc .. (range) left left left
left nonassoc ltgt ! eq ne
cmp nonassoc lt gt le ge (string based) lt gt
lt gt left ltlt gtgt left - . left / x
left ! right ! and unary minus
right nonassoc --
85
Control Structures
  • if statement - first style
  • if (porridge_temp lt 40) print too
    hot.\nelsif (porridge_temp gt 150)
    print too cold.\nelse print just
    right\n

86
Control Structures
  • if statement - second style
  • statement if condition
  • print \index is index if DEBUG
  • Single statements only
  • Simple expressions only

87
Control Structures
  • If you want to omit the then part of a control
    block and have the else part, it is natural to
    say do that if this is false rather than do
    that if not this is true. Use unless (which is
    a reverse if)
  • unless is a reverse if
  • print millenium is here! unless year lt 2000

88
Control Structures
  • statement unless condition
  • unless (year lt 2000)
  • print millenium is here!

89
True/False interpretations
  • 0 converts to 0, so false
  • 1-1 computes to 0, then 0, false
  • 1 converts to 1, so true
  • empty string, so false
  • 1 not or 0, so true
  • 00 not or 0, so true (weird!)
  • 0.00 same as 00
  • undef evaluates to , so false

90
Control Structures For loops
  • for loop - first style
  • for (initial condition increment)
  • code .
  • for (my i0 ilt10 i) print hello\n

91
For loops Style 1
  • for (i0 ilt10 i) print hello\n

92
For loops Style 2
  • for loop (or foreach) - second style
  • for variable (range)
  • code
  • for name (_at_employees_list) print name is
    an employee.\n
  • Takes a list of values and assigns them one at
  • a time to a scalar variable, and executes the
    code
  • with that assignment in effect.

93
For/Foreach loop example
  • _at_a (1,2,3,4,5)
  • print List a ._at_a. \n\n
  • print List b
  • foreach b (reverse(_at_a)) print b
  • Takes a list of values and assigns them one at
  • a time to a scalar variable, and executes the
    code
  • with that assignment in effect.

94
The _ default buffer Style 3
  • May omit scalar variable. Perl will use _ .
  • _at_a (1,2,3,4,5)
  • foreach (reverse(_at_a)) print

95
While
  • while loop
  • while (condition) code
  • cars 7while (cars gt 0) print cars
    left , cars--, \n

96
Until
  • until loop is opposite of while
  • until (condition) code
  • cars 7until (cars lt 0) print cars
    left , cars--, \n

97
Do-while
  • Bottom-check Loops
  • do code while (condition)
  • do code until (condition)
  • value 0do print Enter Value value
    ltSTDINgt until (value gt 0)

98
Next, Redo, Last
  • Loop Controls
  • next operator - go on to next iteration
  • redo operator - re-runs current iteration
  • last operator - ends the loop immediately
  • while (cond) next if a lt 5

99
Control Structures
  • You can break out of multilevel loops using
    labels.
  • Break out of multilevel loops using labels
  • top while (condition) for (car in _at_cars)
    do stuff next top if situation

100
Loop Controls Examples
  • while (qty get_quantities) last if qty
    lt 0 denotes the end next if qty 2
    skip even quantities total qty
    qtycnt
  • print Average of Odd Quantities ,
    total/qtycnt, \n

101
No Switch Statement?!?
  • Perl needs no switch (case) statement.
  • Use if/else combinations instead
  • if (cond1) elsif (cond2)
    elsifelse
  • This will be optimized at compile time

102
Perl regular expressions
  • ? Perl provides a direct translation of regular
    expressions.
  • E.g., regular expression ab in Perl script
  • !/usr/bin/perl This is a Perl script
  • _ ltSTDINgt Read in input to argument _
  • if (/?ab/) print yes\n
  • else print no\n Match _ with ab

103
Perl regular expressions
  • ? The pattern /X/ is matched against the string
  • argument.
  • ? This pattern succeeds if the regular expression
    ab
  • extends from the initial character of the
    input line (?)
  • to the end of the input line ().
  • ? To succeed if ab is contained within a
    string, we
  • only need the pattern /ab/.

104
Simple Regex in Perl
Example if (/abc/) print _ What is
being tested against the regex? Our good old
friend, the _ variable.
105
Simple Regex in Perl
Unlike grep (operated on every line of file),
Perl code looks at just one line. if (/abc/)
print _ Add loop to look at
every line while (ltgt) if (/abc/)
print _
106
Simple Regex in Perl
Like grep, pattern includes zero or more bs
followed by a c while (ltgt) if (/abc/)
print _
Write a Comment
User Comments (0)
About PowerShow.com