Short Perl tutorial

waisttherapeuticSoftware and s/w Development

Nov 4, 2013 (4 years and 1 month ago)

111 views

Short Perl tutorial


Instructor: Rada Mihalcea


Note: some of the material in this slide set was adapted from a Perl course taught at
University of Antwerp


Slide
1

About Perl

1987

Larry Wall Develops PERL


1989

October 18

Perl 3.0 is released
under the GNU Protection
License


1991

March 21

Perl 4.0 is released
under the GPL and the new
Perl Artistic License


Now


Perl 5.14

PERL is not officially a
Programming Language

per se.


Wall’s original intent was to
develop a scripting language
more powerful than Unix Shell
Scripting, but not as tedious as
C.


PERL is an interpreted language.
That means that there is no
explicitly separate compilation
step.


Rather, the processor reads the
whole file, converts it to an
internal form and executes it
immediately.


P.E.R.L. = Practical Extraction and
Report Language


Slide
2

Variables


A variable is a name of a place where some information is stored. For
example:



$yearOfBirth = 1976;


$currentYear = 2011;


$age = $currentYear
-
$yearOfBirth;


print $age;


The variables in the example program can be identified as such because their names
start with a dollar ($). Perl uses different prefix characters for structure names in
programs. Here is an overview:



$: variable containing scalar values such as a number or a string


@: variable containing a list with numeric keys


%: variable containing a list with strings as keys


&: subroutine


*: matches all structures with the associated name



Slide
3

Operations on numbers


Perl contains the following arithmetic operators:


+: sum


-
: subtraction


*: product


/: division


%: modulo division


**: exponent


Apart from these operators, Perl contains some built
-
in arithmetic functions.
Some of these are mentioned in the following list:



abs($x): absolute value


int($x): integer part


rand(): random number between 0 and 1


sqrt($x): square root




Slide
4

Input and output


# age calculator

print "Please enter your birth year ";

$yearOfBirth = <>;

chomp($yearOfBirth);

print "Your age is ",2012
-
$yearOfBirth,".
\
n";




# count the number of lines in a file

open INPUTFILE, “<$myfile”;

(
-
r INPUTFILE) || die “Could not open the file $myfile
\
n”;


$count = 0;


while($line = <INPUTFILE>) {


$count++;

}


print “$count lines in file $myfile
\
n”;



# open for writing

open OUTPUTFILE, “>$myfile”;


Slide
5

Conditional structures


# determine whether number is odd or even


print "Enter number: ";

$number = <>;

chomp($number);

if ($number
-
2*int($number/2) == 0) {


print "$number is even
\
n";

}

elsif (abs($number
-
2*int($number/2)) == 1) {


print "$number is odd
\
n";

}

else {


print "Something strange has happened!
\
n";

}


Slide
6

Numeric test operators

An overview of the numeric test operators:


==: equal


!=: not equal


<: less than


<=: less than or equal to


>: greater than


>=: greater than or equal to


All these operators can be used for comparing two numeric values in an if
condition.



Truth expressions


three logical operators:


and: and (alternative: &&)


or: or (alternative: ||)


not: not (alternative: !)




Slide
7

Iterative structures


#print numbers 1
-
10 in three different ways

$i = 1;

while

($i<=10) {


print "$i
\
n";


$i++;

}


for

($i=1;$i<=10;$i++) {


print "$i
\
n";

}


foreach
$i (1,2,3,4,5,6,7,8,9,10) {


print "$i
\
n";

}



Stop a loop, or force continuation:


last; # C break




next; # C continue;



Exercise:

Read ten numbers and print the largest, the smallest and a count representing how
many of them are dividable by three.


if (
not(defined
($largest)) or $number > $largest) { $largest = $number; }

if ($number
-
3*
int
($number/3) == 0) { $count3++; }



Slide
8

A paranthesis

PERL philosophy(ies)



There is more than one way to do it




If you want to shoot yourself in the foot,

who am I to stop you?



And a comment:
DO

write comments in your Perl
programs!



Slide
9

Basic string operations


-

strings are stored in the same type of variables we used for storing numbers


-
string values can be specified between double and single quotes


-
!!! in the first one variables
will be evaluated
, in the second one
they will not
.



Comparison operators for strings


-
eq: equal

-
ne: not equal

-
lt: less than

-
le: less than or equal to

-
gt: greater than

-
ge: greater than or equal to


Examples:


if ($a eq $b) {


….

}


Slide
10

String substitution and string
matching


The power of Perl!


The
s/// operator

modifies sequences of characters (substitute)

The
tr/// operator
changes individual characters. (translate)

The
m//

operator checks for matching (or in short
//
) (match)


-
the first part between the first two slashes contains a search pattern

-
the second part between the final two slashes contains the replacement.

-
behind the final slash we can put characters to modify the behavior of the
commands.


By default s/// only replaces the first occurrence of the search pattern

-
append a
g

to the operator to replace every occurrence.

-
append an
i

to the operator, to have the search case insensitive



tr translates the characters in the first set of characters into the characters of
the second set

-
if the second set is shorter, the last character is multiplied

-
if the second set is longer, the exceeding characters are truncated


The tr/// operator allows the modification characters

-
c

(replace the complement of the search class)

-
d

(delete characters of the search class that are not replaced)

-
s

(squeeze sequences of identical replaced characters to one character)


Slide
11

Examples

# replace first occurrence of "bug"

$text =~ s/bug/feature/;


# replace all occurrences of "bug"

$text =~ s/bug/feature/g;


# convert to lower case

$text =~ tr/[A
-
Z]/[a
-
z]/;


# delete vowels

$text =~ tr/AEIOUaeiou//d;


# replace nonnumber sequences with x

$text =~ tr/[0
-
9]/x/cs;


# replace all capital characters by CAPS

$text =~ s/[A
-
Z]/CAPS/g;


Simple example:

Print all lines from a file that include a given sequence of characters

[emulate grep behavior]