Upload
tanwir-zaman
View
159
Download
0
Tags:
Embed Size (px)
Citation preview
CS 3430: Introduction to Python and Perl
Lecture 15
Department of Computer ScienceUtah State University
Overview
● Introduction To Perl● Installation, Editing, Documentation● Running Perl programs● Numbers and strings● Control Structures
Perl Overview
Learning Objectives
● Familiarity, not competence● Online resources● Basic coding principles
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
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)
What Perl is Used For● Internet and Web Scripting● Component Integration● Database Programming● Rapid Prototyping● Data Mining
Perl's Strengths● Free● Portable● Mixable● Object-oriented
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
Influences on Perl● AWK● C/C++● Lisp● Pascal● Unix shell● BASIC-PLUS
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
Installation, Editing, Documentation
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
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
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
Running Perl Code
“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”;
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
“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
-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
-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
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
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
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
Numbers and Strings
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
Numbers
● Integers: 0
1972
-10
● Underscores can be used as commas to increase legibility:122038493
122_038_493
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
Numbers● Decimals:
1.234 .5● E notation:
1e2 -5e10 2e-5 1.75e3
● Code sample: numbers.pl
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
Strings
use warnings;
print '\tHello\nworld\n!';
print "\tHello\nworld\n!";
Strings
use warnings;
## this is useful on Windows
## escaping \, aka backwhacking
print "\n";
print "C:\\Perl\\CS3430\\\n";
print 'C:\Perl\CS3430\ ', "\n";
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";
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|;
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
Here-Documents
print <<EOT;
This is a bunch of text.
The quick brown fox ...
Good bye.
EOT
Arithmetic Operators
Addition $x + $y
Subtraction $x - $y
Multiplication $x * $y
Division $x / $y
Modulus $x % $y
Exponentiation $x ** $y
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
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
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;
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;
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
Equality and Relational Operators
> $x > $y
< $x < $y
>= $x >= $y
<= $x <= $y
== $x == $y
!= $x != $y
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)
string_comp.pl
Example
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”;
Scalar Contexts
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 “”
scalar_context.pl
Example
Control Structures
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.”
if_unless.plif_else_if.pl
Example
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
do/while and do/until Loopsdo {
statements;
} while ( condition );
do {
statements;
} until ( condition );
References● www.perl.org● James Lee. Beginning Perl, 2nd Edition, APRESS● Dietel, Dietel, Nieto, McPhie. Perl How to Program,
Prentice Hall