Cs3430 lecture 15

55
CS 3430: Introduction to Python and Perl Lecture 15 Department of Computer Science Utah State University

Transcript of Cs3430 lecture 15

Page 1: Cs3430 lecture 15

CS 3430: Introduction to Python and Perl

Lecture 15

Department of Computer ScienceUtah State University

Page 2: Cs3430 lecture 15

Overview

● Introduction To Perl● Installation, Editing, Documentation● Running Perl programs● Numbers and strings● Control Structures

Page 3: Cs3430 lecture 15

Perl Overview

Page 4: Cs3430 lecture 15

Learning Objectives

● Familiarity, not competence● Online resources● Basic coding principles

Page 5: Cs3430 lecture 15

History

● Larry Wall began to develop Perl in 1987● The language was originally named Pearl, but there

was a language by that name● Perl stands for “Practical Extraction and Report

Language”● Rumor has it that the name Perl came first and the

expansion came later

Page 6: Cs3430 lecture 15

Perl Principles● There is more than one way to do it● Perl: Swiss Army chainsaw of programming

languages● No unnecessary limits● Perl is the duct tape of the Internet (not as true

as it used to be anymore)

Page 7: Cs3430 lecture 15

What Perl is Used For● Internet and Web Scripting● Component Integration● Database Programming● Rapid Prototyping● Data Mining

Page 8: Cs3430 lecture 15

Perl's Strengths● Free● Portable● Mixable● Object-oriented

Page 9: Cs3430 lecture 15

Perl's Weaknesses● Slower than C/C++● Long and rather steep learning curve● Code can be difficult to read

Joke: Perl is a “write only” language Hard even for the original programmer to

read later

Page 10: Cs3430 lecture 15

Influences on Perl● AWK● C/C++● Lisp● Pascal● Unix shell● BASIC-PLUS

Page 11: Cs3430 lecture 15

Resources● http://www.perl.org - site for everything

that is Perl – documentation, IDEs, tutorials, links to helpful resourcesa

● http://cpan.perl.org - Comprehensive Perl Archive Network – a lot of helpful Perl tools and third-party libraries

Page 12: Cs3430 lecture 15

Installation, Editing, Documentation

Page 13: Cs3430 lecture 15

Perl Distributions● Linux, Unix, Mac OS – most likely already installed

● http://strawberryperl.com - Perl distribution for various Windows

“When I am on Windows, I use Strawberry Perl” – Larry Wall

● http://www.activestate.com/activeperl/downloads - Perl distributions for various platforms

● Q: Which version should I install?

● A: Any version 5.8 or higher should work for this class

Page 14: Cs3430 lecture 15

Online Documentation● Main website for documentation is http://perldoc.perl.org/

● ActivePerl installs html version of documentation● If you install ActivePerl, perldoc command

interactively to get documentation on various Perl functions

● C:>perldoc -f print● C:>perldoc -f sqrt

Page 15: Cs3430 lecture 15

Online Documentation● Perl documentation is divided into sections● Sections you might find useful as a beginner:

perlrun: How to execute the Perl interpreter

perldata: Perl data types

perlop: Perl operators and precedence

perlfunc: Perl built-in functions

perlre: Perl regular expressions

perlsub: Perl user-defined subroutines

perlsyn: Perl syntax such as loops and conditionals

Page 16: Cs3430 lecture 15

Running Perl Code

Page 17: Cs3430 lecture 15

“Hello, Perl!” on Windows● Create hello_perl.pl in your favorite editor ● Type in the following two lines into that file:

● Run it from command line (set the PATH variable to point to perl.exe):

C:\Perl\src\>perl hello_world.pl

use warnings;

print “Hello, Perl!\n”;

Page 18: Cs3430 lecture 15

Notes on Perl's Syntax

● Whitespace does not matter as in C/C++● Curly braces { } group code in blocks as in C/C++● Semicolons at the end of statements as in C/C++● Unlike in Python, indentation is not required but makes

code legible

Page 19: Cs3430 lecture 15

“Hello, Perl!” on Linux/Unix

● Call the Perl interpreter directly: /home/user$ perl hello_perl.pl

● Run it as a executable script: Add #!/usr/bin/perl at the beginning of hello_perl.pl

Make the file executable: chmod +x hello_perl.pl

Run it: /home/user$ ./hello_perl.pl

Page 20: Cs3430 lecture 15

-w Warnings Option

● On Windows, Linux/Unix: >perl -w some_program.pl

● On Linux/Unix: place #!/usr/bin/perl -w at the beginning of your program

● On Windows, Linux/Unix: place use warnings; at the beginning of your program

Page 21: Cs3430 lecture 15

-w Warnings Option● If you run warnings_example.pl, you notice that the

Perl interpreter keeps on chugging even if the value of the $x variable is not assigned

● The recommended method is to place use warnings; at the beginning of your file

● Place use warnings; at the beginning of every Perl file you submit as homework

Page 22: Cs3430 lecture 15

Parentheses and Functions● Using parentheses with function calls is optional

print "Hello\n";

print ("Hello\n");● If code looks like a function, it is treated as a function

print 1 * 2 + 5; ## prints 7

print (1 * 2 + 5); ## prints 7

Page 23: Cs3430 lecture 15

Adding Two Numbers● Source code: add_numbers.pl

● $num1 - $ is a type identifier that states that the variable $num1 is a scalar variable, i.e., holds a scalar value

● The statement $num1 = <STDIN>; reads user input from <STDIN> and places it into $num1

● chomp $num1 removes '\n' from the end of the string● $sum = $num1 + $num2; converts the values in $num1

and $num2 to numbers, adds them and places the value into $sum

Page 24: Cs3430 lecture 15

Code Blocks● We can use {…} to group statements in a block● Blocks can be placed inside other blocks● Levels of nesting can be arbitrarily deep● Indentation can be used to increase legibility● Example: blocks.pl

Page 25: Cs3430 lecture 15

Numbers and Strings

Page 26: Cs3430 lecture 15

Basic Data Types

● Perl has four built-in data types: literals, scalars, arrays, and hashes (dictionaries)

● A literal is a value that never changes● In Perl, there are three types of literals: integers,

floats, and strings

● A scalar is a single value that can be either a number or a string

Page 27: Cs3430 lecture 15

Numbers

● Integers: 0

1972

-10

● Underscores can be used as commas to increase legibility:122038493

122_038_493

Page 28: Cs3430 lecture 15

Numbers● Octals start with 0:

01 0523● Hexadecimals start with 0x:

0xFF 0x17abcdef

● Binary numbers start with 0b:0b11111 0b00001

● Underscores are still allowed for readability:0xFF45_FF12 0b1111_0001_1111

Page 29: Cs3430 lecture 15

Numbers● Decimals:

1.234 .5● E notation:

1e2 -5e10 2e-5 1.75e3

● Code sample: numbers.pl

Page 30: Cs3430 lecture 15

Strings● In Perl, string processing is called interpolation ● Single quoted strings are not interpolated with the

exception of \\ and \● Single quoted strings are treated as ordinary text● Double quoted strings are interpolated● In double quoted strings, variables are replaced with

their values and escape sequences are processed

Page 31: Cs3430 lecture 15

Strings

use warnings;

print '\tHello\nworld\n!';

print "\tHello\nworld\n!";

Page 32: Cs3430 lecture 15

Strings

use warnings;

## this is useful on Windows

## escaping \, aka backwhacking

print "\n";

print "C:\\Perl\\CS3430\\\n";

print 'C:\Perl\CS3430\ ', "\n";

Page 33: Cs3430 lecture 15

q and qq● q/some text/ treats some text as a single quoted

string● Delimeters after q do not have to be /, they can be {},

[], <>, or ||

print q/C:\Perl\bin\perl.exe/, "\n";

print q[/usr/bin/perl.exe], "\n";

print q{/usr/bin/perl.exe}, "\n";

Page 34: Cs3430 lecture 15

q and qq● qq/some text/ treats some text as a double quoted

string● Delimeters after qq do not have to be /, they can be {},

[], <>, or ||print qq{\tHe said, "Hello, world!"}, "\n";

print qq[\t/usr/bin/perl.exe], "\n";

print qq|\t'"Hi," said Jack. "Have you read a book today?"'\n|;

Page 35: Cs3430 lecture 15

Here-Documents● A here-document allows you to write large amounts of

text in your program and treat them as strings● A here-document starts with << immediately followed by

a start label, then some text, and a terminating label that must be the same as the start label

● The terminating label must be on a separate line by itself with no semicolon

Page 36: Cs3430 lecture 15

Here-Documents

print <<EOT;

This is a bunch of text.

The quick brown fox ...

Good bye.

EOT

Page 37: Cs3430 lecture 15

Arithmetic Operators

Addition $x + $y

Subtraction $x - $y

Multiplication $x * $y

Division $x / $y

Modulus $x % $y

Exponentiation $x ** $y

Page 38: Cs3430 lecture 15

Operator Precedence● Operators in expressions with parentheses are evaluated

first● Exponentiation operators are applied; if there are multiple

such operators, they are applied left to right● Multiplication, division operators are applied; if there are

multiple such operators, they are applied left to right● Addition and subtraction operators applied; if there are

multiple such operators, they are applied left to right

Page 39: Cs3430 lecture 15

Example

Write a Perl program that evaluates the polynomial y = a*x^2 + b*x + c at the user-supplied values of a, x, b, c.

Solution in operator_precedence.pl

Page 40: Cs3430 lecture 15

Assignment Operators

● Perl provides the C-style assignment operators for abbreviating arithmetic operations in assignment expressions

● Any statement of the formvariable = variable operator expression;

where operator is one of the binary operators (+, -, *, /) can be written in the form

variable operator= expression;

Page 41: Cs3430 lecture 15

Assignment Operators

$c = $c + 5; $c += 5;

$c = $c – 5; $c -= 5;

$c = $c * 5; $c *= 5;

$c = $c / 5; $c /= 5;

$c = $c % 5; $c %= 5;

$c = $c ** 5; $c **= 5;

Page 42: Cs3430 lecture 15

Increment and Decrement Operators

++$c; increment $c by 1 and use the new value of $c in the expression where $c resides

$c++; use the current value of $c in the expression in which $c resides, then increment $c by 1

--$c; Same as ++$c except $c is decremented by 1

$c--; same as $c++ except $c is decrementedby 1

Page 43: Cs3430 lecture 15

Equality and Relational Operators

> $x > $y

< $x < $y

>= $x >= $y

<= $x <= $y

== $x == $y

!= $x != $y

Page 44: Cs3430 lecture 15

String Operators● Perl provides a collection of comparison operators on

string scalars● String operators are: eq (“equals”), ne (“not equals”), lt

(“less than”), gt (“greater than”), le (“less than or equal”), ge (“greater than or equal”)

● Strings are compared alphabetically, with the letters later in the alphabet having “greater” value

● “rabbit” gt “dragon” is true, because the ASCII value of 'r' (114) > the ASCII value of 'd' (100)

Page 45: Cs3430 lecture 15

string_comp.pl

Example

Page 46: Cs3430 lecture 15

String Concatenation and Repetition● The dot (.) is the string concatenation operator

print “a” . “b” . “c” . “\n”;● A string s followed by the string repetition operator (x)

followed by an integer n concatenates n copies of s togetherprint “Yeah” . “!” x 3 . “\n”;

Page 47: Cs3430 lecture 15

Scalar Contexts

Page 48: Cs3430 lecture 15

Numeric and String Contexts● Scalar variables can refer to strings and numbers,

depending on where they occur in the program● Perl converts the value to a string or a number

depending on the context in which the scalar variable is used

● Uninitialized or undefined variables have the special value undef which evaluates differently in different contexts: in a numeric context, undef evaluates to 0; in a string context, it evaluates to “”

Page 49: Cs3430 lecture 15

scalar_context.pl

Example

Page 50: Cs3430 lecture 15

Control Structures

Page 51: Cs3430 lecture 15

if/else & if/elseif/else SelectionLet us implement this pseudocode:

If salesperson's sales >= 100

Print “$1500 bonus!”

Else

If salesperson's sales >= 50

Print “$200 bonus!”

Else

Print “You did not earn your bonus.”

Page 52: Cs3430 lecture 15

if_unless.plif_else_if.pl

Example

Page 53: Cs3430 lecture 15

do/while and do/until Loops

● In addition to the standard while and until loops, Perl has do/while and do/until loops

● while and until loops check their condition first and then execute the body of the loop

● do/while and do/until check their condition after they execute the body of the loop

Page 54: Cs3430 lecture 15

do/while and do/until Loopsdo {

statements;

} while ( condition );

do {

statements;

} until ( condition );

Page 55: Cs3430 lecture 15

References● www.perl.org● James Lee. Beginning Perl, 2nd Edition, APRESS● Dietel, Dietel, Nieto, McPhie. Perl How to Program,

Prentice Hall