Perl Programming I

greenbeansneedlesΛογισμικό & κατασκευή λογ/κού

13 Δεκ 2013 (πριν από 3 χρόνια και 5 μήνες)

65 εμφανίσεις


Perl Programming I

Some materials are taken from
http://cslibrary.stanford.edu/108/EssentialPerl.html

Objectives


Basics of the Perl language


Three data types


Scalars


Arrays


Hashes (next lecture)


Basic control flows


if/unless


while/until


for/foreach


File operations (open, read, write, close)

Introduction to Perl


Perl (
P
ractical

E
xtraction and

R
eport
L
anguage
)

was created in 1986 by Larry Wall
as a simple report generator.


Perl provides the best of several worlds


Powerful

and
flexible
, similar to a high
-
level
programming language such as C.


An
interpreted

language, no compiler needed.


Provides all the features of the script languages
sed

and
awk
, plus features not found in either of
these two languages.

Helpful Resources: Built In
Documentation


perldoc <subject>


Common subjects: perlop, perlvar,
perlfunc, perlsyn


perldoc perltoc for a full list


perldoc

f <function_name>


perldoc

q <FAQ keyword>


perldoc perlfaq for the full FAQ

A Simple Program


vi repeat.pl


#!/usr/bin/perl
-
w


$inputline = <STDIN>;


print “Your input is $inputline
\
n”;


chmod u+x repeat.pl


Note:



<STDIN>

represents a line of input from the
standard input
.


The
print

function sends data to the
standard output.


The
;

token at the end of the statement is a special token
that tells Perl the statement is complete.


-
w

is a flag that tells Perl to turn on warning messages.

Variables


Three major types of Perl variables


Scalars


Arrays


Hashes (next lecture)

Scalars


A
scalar

variable contains a single value.


All of the standard types from C can be stored
in a scalar variable


int, float, double, char, etc


No declaration of type of variable

Scalar Names


Scalar variable name starts with
$


Next character is a letter or a underscore


Remaining characters: letters, numbers, or
underscores.


Name can be up to 255 characters long


Legal samples: $f, $bar, $z1, $d_3

Perl Variable Names are Case
-
sensitive


All Perl variable names, including
scalars, are case
-
sensitive. This means
that the following variables are different:

$VAR

$var

$Var



Scalar Examples

$var = <STDIN>;

# get input from keyboard

$num = 42;

$var1 = 5 + 6 * 4;

# $var1 = 29

$var2 = $var1 * 6;

# $var2 = 29*6


$grade = 99.44;



$name = "Paul";


$Big_string = “The Quick Brown Fox…";

Example: interacting with user and
chomp function

#!/usr/bin/perl

print ("Enter the distance to be converted:
\
n");

$originaldist = <STDIN>;

chomp

($originaldist);

$miles = $originaldist * 0.6214;

$kilometers = $originaldist * 1.609;

print ($originaldist, " kilometers = ", $miles, " miles
\
n");

print ($originaldist, " miles = ", $kilometers, " kilometers
\
n");




Note:
The function
chomp

removes the trailing newline character if
present.

Interchangeability of Strings and
Numbers


Perl converts automatically between
numbers and strings as required. In scalar
variables, a value that was assigned as a
string can be used as an integer whenever
it makes sense to do so, and vice versa.

$string = "43";

$number = 28;

$result = $string + $number;
# result = 71;

Interchangeability of Strings and
Numbers (Contd)


The dot operator (.) concatenates two
strings.

$num = 42;

$string = "The " . $num . " ultimate" . " answer";

# $string is "The 42 ultimate answer"


Arrays


A collection of scalars is an
array
.


An array variable name starts with
@


@trees = ("Larch", "Hazel", "Oak");



Array subscripts are denoted by brackets.


$trees[0]
, is the
first

element of the @trees array.


Notice that individual array elements are scalars,
so they start with $.

Arrays


Mixing scalar types in an array is not a
problem. The code


@items = (15, " 45.67 ", "case");


print "Take $items[0] $items[2]s at
\
$$items[1]
each.
\
n";


results in the following:


Take 15 cases at $45.67 each.


Accessing an Element in an Array


Index of array begins with zero


@array = (1, 2, 3, "HUSKER");


$array[3] = 5;
# (1, 2, 3, 5)


$scalar = $array[1];
# $scalar = 2;


$index = 2; $scalar = $array[$index];

# use
a scalar variable as a subscript; $scalar = 3;


Accessing an Element in an Array
(Contd)


Perl arrays are not bounds checked. If code attempts
to read an element outside the array size,
undef

is
returned. If code writes outside the array size, the
array grows automatically to be big enough.


undef

(undefined value) is treated as "0" when used as a
number, or the empty string "" when used as a string.


@array = (1, 2, "hello", "there");


$sum = $array[0] + $array[27];

# $sum is now 1,
since $array[27] returned undef


$array[99] = "the end";

# array grows to be size 100

Length of Array


Retrieving the length of an array:

$len = @array;




Example:


@list = ("UNL", "HUSKER", "university");


$len = @list;


# $len is 3.

sort operation


Many of Perl's built
-
in functions take
arrays

as arguments. One example is
sort
, which
takes an array as an argument and returns
the same array, sorted alphabetically.


The code


print sort ("Beta", "Gamma", "Alpha" );



prints AlphaBetaGamma.

join operation


You can make this code neater by using another
built
-
in function, called
join
.


join

function takes two arguments: a string to connect
with, and an array of strings to connect. join returns a
single string that consists of all elements in the array
joined with the connecting string.


The code


print join (
"

:
", "
Name
", "
Address
", "
Phone
"
);



returns the string
Name : Address : Phone
.

join operation (Contd)


Because
sort

returns an array, you can feed
its output straight into
join
. The code


print join(",", sort ("Beta", "Gamma", "Alpha" ) );


prints
Alpha, Beta, Gamma
.

split operation


split

a string into an array of strings.



$line = "This:is:a:string";


@array = split (/:/, $line);


#array is ("This", "is", "a", "string").



@array = split(/
\
s+/, $line2);
# split according
to white space.

push operation


push

adds the elements to the end
(right hand
side)

of the array and returns the new number
of elements in the array.


The code


@a = (1);


$num = push(@a,2,3,4,5);


print("Added ", $num
-
1, " elements to array: ",@a,"
\
n");


Print
Added 4 elements to array: 12345

pop operation


pop

removes the last element from the array
and returns that element.


The code


@a = (1,2,3,4);


print (pop(@a), " leaves ",@a,"
\
n");


print
4 leaves 123

shift operation


Remove an element from the
front

of an
array.


@a = (1, 2, 3);


$first = shift(@a);



# $first = 1, @a = (2, 3)


unshift operation


unshift

inserts the list at the front of the array
and returns the new number of elements in
array.


The code


@a = (a, b, c);


$ret = unshift(@a, 1, 2, 3);


print("Array has $ret elements:",@a,"
\
n");


print
Array has 6 elements:123abc

Relational Operators

if/unless

1.
if (EXPR) BLOCK

2.
if (EXPR) BLOCK else BLOCK

3.
if (EXPR) BLOCK elsif (EXPR) BLOCK …
else BLOCK


The
block

is delimited with
curly brackets
,
containing zero or more statements.


Unless (EXPR) BLOCK


Analogous to English meaning of “unless”


Can use elsif and else with unless as well

if examples

1.
if ( $a == 1 ) {



print “It’s one.
\
n”;


}

2.

if ( $a == 1 ) {



print “It’s one.
\
n”;



}


else {



print “It’s not one.
\
n”;


}

The parenthesis and
Curly Brackets are
required!

3.

if ( $a >= 1000 ) {



print “A big number.
\
n”;


}


elsif ( $a <= 10 ) {



print “A small number.
\
n”;


}


else {



print “Something else.
\
n”;


}

Another Usage


statement if expression


statement unless expression


Parentheses and curly brackets are not required.



$max = 100 if $min < 100;


The statement is executed if the logical expression
is true and is not executed otherwise.


print “Success” unless $error > 2;


The statement is not executed if the logical
expression is true and is executed otherwise.

while/until loops


while (
expr
) {




block of statements


}


until (
expr
) {



block of statements


}


The parenthesis and curly brackets are required!


The
while

statement loops while its conditional expression is
true
.


The
until

statement loops until its conditional expression is true
(that is, it loops as long as its conditional expression is
false
).

while loop example

#!/usr/bin/perl
-
w

$done = 0;

$count = 1;



print (“Start of loop.
\
n");


while ($done == 0) {


print ("The value of count is ", $count, "
\
n");


if ($count == 3) { $done = 1; }


$count = $count + 1;


}



print ("End of loop.
\
n");

until loop example

#!/usr/bin/perl
-
w

$done = 0;

$count = 1;



print (“Start of loop.
\
n");


until ($done != 0)

{


print ("The value of count is", $count, "
\
n");


if ($count == 3) { $done = 1; }


$count = $count + 1;


}



print ("End of loop.
\
n");

for loops


Perl has two styles of for.


First kind if virtually identical to C/C++


for

(INIT; TEST; expr3) {




block of statements


}


The parenthesis and curly brackets are required!


Example:

for ($count=0; $count<5; $count++) {


print ('$count = ', $count, "
\
n");

}

foreach loops


Second kind of for loop in Perl




foreach

localvar (listexpr) {



block of statements


}



Example:


@words = ("Here", "is", "a", "list.");


foreach

$word (@words) {



print ("$word
\
n");


}

How Perl Accesses Disk Files


Perl uses
filehandles

to reference files.


Filehandles are written in all upper
case, like FILE_OUT or SOCK.


File Open

Syntax:
open (filehandle, filename);



filehandle

represents the name you want to use in
your Perl program to refer to the file.


filename

represents the location of the file on your
machine.


If open returns a nonzero value, the file has been
opened successfully.


If open returns 0, an error has occurred.


if (open(MYFILE, "test.txt")) {


# here's what to do if the file opened

}


File Open Modes


Read mode: (default mode)
open (FILE, "test.txt");



Enables the program to read the existing contents of
the file but does not enable it to write into the file


Write mode:
open (FILE, ">test.txt");



Destroys the current contents of the file and
overwrites them with the output supplied by the
program


Append mode:
open (FILE, ">>test.txt");



Appends output supplied by the program to the
existing contents of the file

Close a File


Syntax:
close (filehandle);


close

requires one argument: the file
handle representing the file you want to
close.



Once closed, you cannot read from it or
write to it without invoking open again.


Read From a File


Syntax:
$var = <filehandle>;


Read one line from a file and store in $var.



A program that reads lines from a file and prints them on the screen
.



#!/usr/bin/perl
-
w


if ( open(MYFILE, “test.txt") ) {



$line = <MYFILE>;

# read a line from file



while ($line ne "") { # loop until the end of file




print ($line); # print on the screen




$line = <MYFILE>;
# read a line from file



}


}


close(MYFILE);

Write to a File


Syntax:
print filehandle contents;



A program that opens two files and copies one into
another.


#!/usr/local/bin/perl
-
w

open(INFILE, “test.txt")


# open in read mode

open(OUTFILE, ">test.txt.bak");

# open in write mode

$line = <INFILE>;

while ($line ne "") {

print OUTFILE ($line);

# write into a file

$line = <INFILE>;

}

close(INFILE);

close(OUTFILE);

A Comprehensive Example


A program that tests whether a file exists before opening it for
writing.



#!/usr/bin/perl
-
w


unless (open(INFILE, "infile")) {



die ("Input file cannot be opened.
\
n");



}


if (
-
e "outfile") { die ("Output file already exists.
\
n");}



unless (open(OUTFILE, ">outfile")) {



die ("Output file cannot be opened.
\
n");


}


$line = <INFILE>;


while ($line ne "") {



print OUTFILE ($line);



$line = <INFILE>;


}


close(INFILE);


close(OUTFILE);

Terminating a Program Using die



Syntax:
die (message);



When the Perl interpreter executes the die function, the
program terminates immediately and prints the
message passed to die.


Example


die ("Stop this now!
\
n");



prints the following on your screen and terminates the
program:



Stop this now!

Next Lecture


More Perl programming


Hash variables


Subroutines


Double quote, single quote and backslash


Use command
-
line arguments as values