Monday 26 May 2014

Introduction to PerlProgramming

Introduction to PerlProgramming
Perl vs.other
programming languages

Mostprogramming languages--such as C, C++,
VisualBasic, etc.--are compiled languages.

To run a program,you create a text documentwith the
code, run a compiler on it to convert it into machine
code for yourOS, and then run it.

Perlin an interpretedlanguage, like Java,
Pascal, awk, sed, Tcl, orSmalltalk.

To run a program in such a language, you create a text
document and tell the interpreter (or Virtual Machine) to
run it as a program.The interpreter checks it, compiles
it into machinecode, and runs it.

The 2-step process of interpreted languages makes them
slightly easier to work with. You canconstantly check
yourcodeby running it after every change.


Introduction to PerlProgramming
History of Perl

Perlwas designed in the mid 1980s by Larry Wall,
then a programmeratUnisys, and self-described
"occasionallinguist".

He combined usefulfeatures of severalexisting
languages with a syntax designed tosound as
much as possible like English.

Since then, Perlhas mushroomed intoa powerful
and popularlanguage, with lots of modules
contributed by the open-source community.

Perlis designed tobe flexible, intuitive, easy, and
fast;this makes itsomewhat"messy".

Perl has been called"a Swiss-Army chainsaw"

Perl is also known as "the duct-tape of the Internet"

Introduction to PerlProgramming
Perl culture

In many ways, Perlis a language for"hackers",
notforcomputerscientists. Perlis disdained by
people whopreferlanguages like C, which are
more rigid and closertomachine code.

Larry Wall's perspective is this:

"Perl is a language for getting your job done."

Twootherslogans thatare key toThe PerlWay:

"Easy things shouldbeeasy,and hard things
shouldbepossible."

TMTOWTDI: "There's More Than One Way To Do It."

Introduction to PerlProgramming
Howyouget Perl

One of the greatthings aboutPerlis thatitis
entirely free. Italsoruns on any platformout
there. You can getthe source code ora binary
distribution fromthe web.

The main Perlrepository is CPAN:the
Comprehensive PerlArchive Network

http://www.cpan.org

There is a binary distribution forWindows thatyou
can getdirectly fromthe makers, ActiveState:

http://activestate.com/

Alsocheck outthese sites:

http://perl.com/  http://www.perl.org/

Introduction to PerlProgramming
III. Perl basics
Introduction to PerlProgramming
Executing ascript: way #1

There are twoways of running a Perlscript:atthe
command line and froma textfile.

Forvery shortscripts, you can just type the
whole program atthe command line and watch
the computerrun it.
C:\>perl -e "print 'Hello, World!'"
Hello,World!
C:\>

Introduction to PerlProgramming

Forlongerscripts (and ones you would like to
reuse), you create a plain-textdocumentwith the
programcode and then tellthe Perlinterpreterto
run this program, usually on the command line.

Save as "myprogram.pl":
#!/usr/bin/perl
print 'Hello, World!';

Then, on the command line:
C:\>perl myprogram.pl
Hello,World!
C:\>
Executing ascript: way #2
Depending on your
system, you might be
able to run programs
in various ways!
Try these out:
perl myprogram.pl
myprogram.pl
myprogram

Introduction to PerlProgramming
Writing ascript

Perlscripts/programs are plain-textdocuments
(generally ASCII), usually with the extension .pl,
though this isn'tstrictly necessary.

You can write scripts in any word processor,
though I recommend thatyou not use MSWord
oranotherprocessorthatby defaultsaves
documents in some binary (i.e., non plain-text)
format.

See the wiki for linksto editor applications.

It's alsovery helpfultouse a constant-width
(monospaced)font, such as Courier New,
because then you willbe able toline up your code
easily.

Introduction to PerlProgramming
Writing ascript

We generally starta Perlscriptwith the "shebang"
line, which looks something like one of these:
#!/usr/bin/perl
#!/usr/local/bin/perl
#!/usr/local/bin/perl5
#!/usr/bin/perl-w
etc.

This is notnecessary on many systems, butwhen
itis, itis, soit's a good habittogetinto.

The purpose of this line is totellthe serverwhich
version of Perltouse, by pointing tothe location
in the serverdirectory of the Perlexecutable.
very useful!

Introduction to PerlProgramming
A first program

Let's write a firstprogram. Open yourtext-editor
of choice and type the following:
#!/usr/bin/perl
print "Hello, World!\n";

Then save the file as "hello_world.pl". Preferably,
save allyourscripts in the same directory. I call
my directory "scripts". (I don'tuse "perl", because
thatwhere allthe Perlfiles are.)

Nowwe need totellthe interpretertoexecute the
script. We dothis atthe command line.

In UNIX, this iscalled a shell;in Windows, a command
prompt; in Mac OS X, a Terminal window.

Introduction to PerlProgramming
Getting to thecommand line

In Windows:Click on CommandPrompt. Toget
there, you may have tolook under
Start->All Programs->Accessories

In MACOS X:Click on Terminal. Togetthere,
you may have tolook under
Applications->Utilities

In UNIX:If you're running UNIX, you are in a
shell, provided you're logged on. The same goes
forX-Windowora similarprogram.

Introduction to PerlProgramming
Navigating intheshell

Note:The prompt may look differentways,
depending on yoursystem. Usually, ittells you
whatdirectory you're in. Note thatit's often
customizable. Here are some examples:
C:\scripts>
/scripts$
[Some-Computer:~/scripts]%

You really only need toknowone command toget
around in the shell: cd. Butitalsohelps toknow ls
(dirin Windows)and pwd.

Move to dir 'scripts' move up one dir
cd scripts cd ..

Introduction to PerlProgramming
Basic Perl syntax

Perlthinks of "lines"differently fromhumans.
Forus, the mostimportantthing is the carriage
return;forPerlitis the semicolon.

Alllines of code in Perlmustend with one of two
things:a semicolon or curly braces:
print "Hello.";
sub{print "Hello."}

A line of code, called a statement, is basically a
single instruction tothe computer;itsays, "Do x."
Itcan extend overmore than one line of the page.

Anything in {}is called a block. A block can
contain severalstatements

Introduction to PerlProgramming
Comments

Any line thatbegins with the character # is
treated by Perlas a comment andis ignored.

This means thatyou can putlots of comments for
humans toread in yourcode, withoutaffecting the
program. This is a very good idea.

The #can actually come atany pointin the line:
whatevercomes afteritwillbe ignored. Butin
thatcase whatcomes before ithad betterbe a
valid line of code!
# Thisnext line sorts alphabetically
@names= sort (@names); # () optional

Introduction to PerlProgramming
Quotemarks

Perlmakes use of three basic kinds of quote
marks:single (' '), double (""), backquotes (``)

You willusually wanttouse double quotes. As a
generalrule, use the others only if you have to.

Double quotes allow variable interpolation. That
means thatthis code:
$name = "Alejna";
print "Hello, $name!\n";

willprintthis:
Hello,Alejna!
These are the
quotes to watch!

Introduction to PerlProgramming
Quotemarks

Single quotes willpreventinterpolation. That
means thatthis code:
$name = "Alejna";
print 'Hello, $name!\n';

willprintthis:
Hello,$name!\n

Backquotes (``)run an externalprogramand
grab the output. You willrarely, if ever, use these.

Introduction to PerlProgramming
Backslashinterpolation

Perlhas a numberof specialcharacters thathave
a particularmeaning within double quotes an in
regularexpressions. Here are twoimportantones:
\n means "newline"
a.k.a. "carriage return"
\t means "tab"

So, here's whatwe can type and whatwe'llget:
print "Name:\tBecky\nEyes:\thazel\n";
Name: Becky
Eyes: hazel

Introduction to PerlProgramming
IV. Variables
Introduction to PerlProgramming
Datatypes inPerl

Mostdata is basically eithera string ora
number, or a bunchof strings or numbers.

A string is characterdata:"froggy", "11-30-04".

Always write strings within quote marks, as above.

A number is exactlywhat you think itis.

Note, however, thata given piece of data that
looks like, say, 300, can be treated like a number
(e.g., 300+1)orlike a string (e.g., through
concatenation: 300a).

Unlike otherprogramming languages, Perltakes a
very relaxed attitude toward this distinction. It
basically looks atwhatyou're trying todoand
treats the data as the appropriate type.

Introduction to PerlProgramming
Variables

The conceptof the variable is fundamentalin all
programming languages. A variable is essentially
a placeholderfora value.

We knowvariables frombasic algebra:

In x + 1 = 5, x is a variable.

Use of variables in programming differs a bitfrom
algebra:We spend a lotof time creating variables,
assigning values tothem, changing the values,
and reading the values.

Virtually alldata is stored in variables. We
manage this information through operators
(like +)and functions (like print)

Introduction to PerlProgramming

In Perl, the three mostimportanttypes of
variables are the scalar, the arrayand the hash.

A scalar is a variable thatholds a single value.
Scalarnames begin with $:
VARIABLE VALUE
$name = "Aisha";
$age  = "20";
Scalars

Introduction to PerlProgramming
Arrays and hashes

There are twokinds of variables thathold multiple
pieces of data: arrays and hashes.

An arrayis a variable thatholds multiple values
in series. Array names begin with @:
@names= ("Howard", "Leslie", "Bob");

A hash is a variable thatholds pairs of data. Hash
names begin with %:
%traits =("name" => "Howard",
"age" => "30", "eyes" => "brown")

Introduction to PerlProgramming
Variablenames

The name of a variable (whetherscalar, array, or
hash)begins with the specialtype-indicating
character($, @, or %,respectively), and then
can contain any combination of letters, numbers,
and underscores.

However, the first character after the $, etc. must be a
letter orunderscore, not a number.

Also, case IS distinctive.

Examples of valid names:
$time_of_arrival, $Time_of_Arrival
$timeofdeparture, $TOD
$Time4U2Go (ifyou're childish)

Introduction to PerlProgramming
Good naming practice

When you choose variable names, choose
illustrative ones, notobscure ones:
BAD                              GOOD
$x = "John"; $first_name = "John";
$y = "Bates"; $last_name = "Bates";

I make a pointof using singularnames forscalars
and pluralnames forarrays and hashes:
$person ="Christine";
@people =("Christine", "Jean");

Introduction to PerlProgramming
Two kinds of operators

The importantone towatch outforis the
"smooth operator". No, justkidding.

A usefuldistinction tokeep in mind is that
between assignment operators and
comparisonoperators.The former givea
value toa variable, and the latter test the value
of a variable.

To set the value of a variable:
$limit= 100;

To testthe value ofa varable:
if ($number == 100) {print "Limit!"}
If thiswere a speech act,
it would bea performative.
If thiswere aspeechact,
itwould be a question.

Introduction to PerlProgramming
Working withscalars

We assign a value toa scalarusing the assignment
operator =, whetherwe are dealing with strings or
numbers.
$name = "Eliani";
$grade = 100;

We can performmath on a scalarif itmakes sense
todoso:
$grade = ($grade * 30)/100;

We can perform concatenation on strings with
the . operator:
$name = $first_name . " " . $last_name;
# now $name is, e.g., "Mary Hughes

Introduction to PerlProgramming
Working witharrays

We can assign values toarrays in various ways.
The moststraightforward is touse parentheses,
which create a "listcontext":
@grades =("98", "84", "73", "89");

The values in an array are numbered (or
indexed), starting with 0, rather than 1. We
can access any value in an array by referring to
its numericalindex in square brackets:
print "$grades[0] and$grades[2]";
98 and73

Note thatwe use $ ratherthan @, because here
we're referring nottothe whole array, buttoone
elementin it, which is a scalar.

Introduction to PerlProgramming
Working witharrays

When we printan array, itmakes a difference
whetherwe putitin double quotes ornot;if we
do, we getspaces between the elements.
@VOTs = ("400","378", "352");
print @VOTs;
400378352
print "@VOTs";
400378 352
print '@VOTs'; # to review
@VOTs

Introduction to PerlProgramming
Input

Perlneeds data tointeractwith. This data typically
comes fromone of three sources:keyboard input,
files, orthe system(the server).

We're only going to cover the first of these today.

Inputfromthe keyboard is sostandard thatwe
callit"standard input", abbreviated STDIN.

Here's howwe getsome inputfromthe keyboard:
$input= <STDIN>;

This assigns to $input whateverthe usertyped.
Unfortunately, this alsoincludes the newline from
when they hit"Enter", sowe take thatoff like so:
chomp ($input);# the()are optional

Introduction to PerlProgramming
V. Conditionals and loops
Introduction to PerlProgramming
Conditionalstatements: if

Of course, the powerof programs comes from
theirinputtoreactdifferently todifferentdata.
The conditional statement is the key tothis.

The if statementhas twoparts:a condition,
which is evaluated, and a block, which is
executed if the condition evaluates tobe true.
if ($price >100) {
print "Too expensive!\n";
}

Introduction to PerlProgramming
Conditional statements: elsif

An if statement can optionally be followed by an
elsifstatement. This is evaluated after the if
statement only ifthe previouscondition
evaluated(the ifstatement's)wasfalse.
The twoblocks willneverboth be exectuted.
if ($price >100) {print"expensive"}
elsif ($price <10) {print "bargain!"}
elsif ($price <40) {print "cheap"}

Again:If the ifstatementevaluates totrue, the
elsif statements are justskipped. Similarly, if the
first elsif evaluates totrue, the second is skipped.

Introduction to PerlProgramming
Conditional statements: else

An elsestatementis a specialkind of elsifthat
covers allremaining conditions. In linguistics, this
is known as "the elsewhere condition".
if ($grade <60) {
print "Failing grade!: $grade\n";
}
else {print "Gradeis$grade.\n"}

Note thatthere is nocondition tobe evaluated in
an elsestatement, because it's the "garbabe can"
category and is always true.

Introduction to PerlProgramming
Loops

A majorreason we use computers is thatthey can
dothe same thing many times withoutgetting
tired orneeding coffee. We getthemtorepeat
actions using iterative or looping constucts.

There are three main types of loop statement,
which are allrelated butspecialized fordifferent
uses: for, foreach, and while statements.

Introduction to PerlProgramming
VI.  Exercises
Introduction to PerlProgramming
Exercise1

Here is a commandline scriptthatprint"Hello,
world!"(Windows version—others may wantto
use single quotes):
perl -e "print qq/Hello,World!\n/;"

Note thatinside the " ", we use qq/ / instead; this is
because we can't nestdouble-quotes. These are
equivalent:
"hello" =qq/hello/

Write a scripton the command line thatgreets
you instead of the world.

Then add some code sothatitprints two
messages on twolines.

Introduction to PerlProgramming
Exercise2

Here is a program(tobe written in a textfile)that
prints again on the screen whateveryou type.
Modify itsothatitasks foryourname and greets
you by name.

Name: Call it 'greet.pl'.
#!/usr/bin/perl-w
print "Type something: ";
$something =<STDIN>;
chomp $something;
print "$something\n";
Thisis a terrible variable name. Change
it to something more appropriate

Introduction to PerlProgramming
Exercise3

Write a programthat, given the base formof a
verb (through STDIN), outputs the correct3rdperson singularform.

Name: Call it 'conjugate.pl'.

NOTE:Don'tforget about irregular forms!

NOTE:You can leave out all negative forms.

NOTE:You can also ignore forms like "watches".
(We'll do those ones once we get to regular expressions)

HINT:You willprobably wanttouse the following
things:
if   elsif  else   eq  .

Introduction to PerlProgramming
VII.  Morestuff
Introduction to PerlProgramming
Opening files

Perlmakes itfairly easy toload data fromfiles. To
dothis we use the open and closefunctions, and
the "angle-operator" <>.

Here's a simple example:
$input_file = "bigoldfile.dat";
open (INPUT,"$input_file");
while ($line= <INPUT>) {
print "$line";
}
close (INPUT);

INPUTis what's known as a filehandle. It's a
temporary name fora file. STDIN is a filehandle too.
Note that thisprints to
STDOUT, or the screen.

Introduction to PerlProgramming
Creating files

We can use the same commands tooutputtoa file
thatthe programcreates.
$input_file = "bigoldfile.dat";
$output_file= "output.txt";
open (INPUT,"$input_file");
open (OUTPUT, ">$output_file");
while ($line= <INPUT>) {
print OUTPUT "$line";
}
close (INPUT);
close (OUTPUT);
This > makes allthe difference.
It means that this file is being
writtento,not read from.

Introduction to PerlProgramming
The'split'function

The function split enables us toeasily transforma
scalartoan array, by splitting the scalarup on
spaces oranothercharacter.
$sentence= "Sue and I split up.";
@words= split(/ /, $sentence);
print "$words[4]\n";
up.

We can alsospliton commas, etc.
$list = "Eenie,meenie, miney,moe";
@words= split(/,/, $list);
print "$words[3]\n";
moe
That's a space.

Introduction to PerlProgramming
Counting elements inanarray

We often wanttoknowhowmany elements are in
an array. There are three ways togetthis info.

The function scalar:
@people =("Moe", "Larry", "Curly");
print scalar(@people). "\n";
3

Use of "scalar context":
$count= @people;
print "$count\n";
3

Use of $#, which gives the last index of an array:
print "$#people";
2

Introduction to PerlProgramming
Finding thelengthof astring

The function length can be used tofind tolength
in characters of a scalar.
$string ="abcdefghij";
$howbig =length($string);
print "$howbig\n";
10

Introduction to PerlProgramming

The'sort'function

You can sortthe elements of an array orthe keys
of a hash with the function sort. BUT:Bydefault,
itsorts both strings and numbers alphabetically!
@array= ("Betty","Cathy","Abby");
@array= sort(@array);
print "@array\n";
Abby Betty Cathy

But watch out:
@array= ("3", "40", "24", "100");
@array= sort(@array);
print "@array\n";
100243 40

Introduction to PerlProgramming
Sorting array keys

A very common type of loop makes use of the
functions sort and keys.The latteryields allthe
keys (notthe values)in an array.
%signs= ("Frank" => "Capricorn",
"Amanda"=>"Scorpio");
foreach $person(sortkeys %signs) {
print"$person: $signs{$person}\n";
}
Amanda: Scorpio
Frank:Capricorn
Introduction to PerlProgramming
Adding elements to arrays

There are twoways of adding newelements to
existing arrays.

If we knowthe index we wantthe elementto
have, we can dothis:
@numbers = ("210","450", "333");
$numbers[3] = "990";

If we simply wanttoadd an elementtothe end of
an array, we can use push:
push(@numbers, "990");

In eithercase, @numbers is now:
210450 333 990
Introduction to PerlProgramming
Taking elements out of arrays

The reverse of push is pop, which takes removes
the lastelementfromthe array:
@numbers = ("210","450", "333");
$last = pop(@numbers);
print "$last\n";
333

Note thatthis is differentfromsaying
$last = $numbers[2];
because this doesn't remove the element fromthe
array. After pop, the array willhave only 2
elements!

No comments: