Introduction to Perl
This lecture notes is based on Prof Doreen De Leon's lectures.
Reading
Learning Perl, Chapter 2.
What is Perl?
- Stands for Practical Extraction and Report Language.
- Purpose
- Help with common tasks that are too portability sensitive for the UNIX shell, but not something you want to code in C++.
- Good for
- manipulating text files line-by-line;
- anything with strings;
- CGI (Common Gateway Interface)- our main purpose for studying it;
- small programs in general.
-
Created by Larry Wall for his own purposes, then added to by others.
Start Doing Perl
On PC
Download
- Download Perl at ActiveState.com
- Fill in a registration form, download the one file with .msi extension.
- install the software, say yes to every questions
Run a Perl program.
- Type in a program using any editor you like, don't use wordpad!, a sample program is
print "Hello World\n";
- Save it as "hello.pl"
- open a DOS prompt and changes to the folder that contains the file
hello.pl
- Type
perl -w hello.pl
If the following message shows up:
'PERL' is not recognized as an internal or external command,
operable program or batch file.
That means the path is not setting correctly.
The problem will probably go away after you restart your computer.
Otherwise, you have to set the path. E-mail me and I will
let you know how to set the path. Meanwhile, you can use
C:\perl\bin\perl -w hello.pl
- You can see the output
Hello World
On Unix
Scalar Data
- Either a number (integer or floating point) or a string of characters.
- Internally, Perl computes numbers with double precision floating point values.
- Literal: the way a value is represented in the text of a Perl program.
- Numeric literal: Don't use leading zero, since Perl supports octal (e.g., 0258=21) and hexadecimal (0x1516=21).
- Strings: sequences of characters � two types
- Single-quoted
What you see is what you get except
- \' to get a single quote into a string
- \\ to get a backslash into a string
- Double-quoted
Like a C++ string.
Interpret \ as specifying escape characters
Some escape characters:
- \n = newline
- \r = return
- \b = backspace
- \t = tab
- \" = double quotes
- \\ = backslash
Example
print 1.25, "\n", 255.1, "\n", 7.25e3;
Output
1.25
255.1
7250
print 'abc\n'; #abc\n
print "\nabc\n";# newline abc newline
print 'I\'m Charles.'; #I'm Charles
Output
abc\n
abc
I'm Charles.
Scalar Operators
For Numbers
- +, -, *, / (always floating point)
- **: exponentiation
- If the result can't fit into a double precision number, get a fatal error.
- %: modulus, Changes floating point operands to integers by truncating.
- Comparison:
<, >, <=, >=, ==, !=
Example
print 1.1**2; #1.21
print "\n"; # new line
print 7.5%3; #1
1.21
1
For Strings
- Concatenation operator: . (dot)
Example:
- String repetition operator: x
Left operand is a string, right operand is a number
Makes right operand copies of left operand
If right operand is floating point, it is truncated to get an integer
Examples:
-
Comparison operators: eq, ne, lt, gt, le, ge
- Compare strings character by character, using ASCII values.
Warning: In ASCII, capital letters come before lower case ones, and numbers come before capital letters.
Warning: 5 < 14 is true, but 5 lt 14 is false.
- Order of operations based on precedence table (see p. 32 of Learning Perl).
print "hello"."world"; #helloworld
print "\n"; # new line
print "hello".' '."world"; # hello world
print "\n"; # new line
print "hello" x 3; #hellohellohello
print "\n"; # new line
print 2.3; # 2.3
print "\n"; # new line
print 2 . 3; # 23
print "\n"; # new line
print 2 x 3; # 222
helloworld
hello world
hellohellohello
2.3
23
222
if("abc" lt "def") {
print "abc < def\n";
}
Conversion Between Numbers and Strings
-
If a string value is used as an operand for a numeric operator, the string is converted to its equivalent numeric value.
-
With the
-w option, you get a warning.
-
Any trailing non-numerical characters and leading whitespace ignored.
-
If the string is not a number, e.g., "boo", then it converts to 0 with a warning.
-
If a numeric value is used as an operand for a string operator, the numeric value is expanded into the string that would have been printed for the number.
print "2" + "3"; # 2 + 3
print "\n";
print "2".3; # 23
print "\n";
print 2 x 3; # 222
print "\n";
print "12abc"*"5abc"; # 12*5
5
23
222
60
Scalar Variables
- Hold a single scalar value.
- Variable names: begin with a $, followed by a letter or an underscore, then by more letters, digits, or underscores.
- Names are case-sensitive.
- Variable names should be meaningful.
- Scalar variables in Perl always referenced with the leading $.
Scalar Operators and Functions
- Assignment (=)
- Notes:
- The left hand side operand must be an lvalue (valid storage location, e.g., a variable).
- $x = 1 has a value (it is the value of the variable $x after assignment, i.e., 1).
- Examples:
- Binary assignment operators: +=, .=, *=, /=, %=, .=, x=, ||=, &&=, **=, etc.
- Examples:
- Autoincrement/autodecrement: ++/--
- Exactly analogous to C++.
- The operand must be a scalar variable.
$x = 123;
$x+=2;
print $x;
print "\n";
$x = "abc";
$y = "def";
$z = $x.$y;
print $z;
print "\n";
print $x x 3;
print "\n";
print 125, " is a number but ", $x, " is not a number.\n";
125
abcdef
abcabcabc
125 is a number but abc is not a number.
The chop and chomp Functions
- chop
-
Takes a single argument (the name of a scalar variable) and removes the last character from the string value of the variable
-
The value returned by the function is the discarded character.
-
If chop is given an empty string, it does nothing and returns nothing. Get an error if using the -w switch.
- chomp
-
Takes a single argument (the name of a scalar variable) and removes the trailing newline character, if present.
-
Returns the number of characters removed.
$x = "abcde";
print $x, "\n";
chop($x);
print $x, "\n"; #abcd
$x = "abcde\n";
#print $x, "\n";
chomp($x); # the \n is removied
print $x, "\n";
print "how many empty lines?";
abcde
abcd
abcde
how many empty lines?
Variables in Strings
-
In a double-quoted string, any variable names are replaced by the stored value of the variable (called variable interpolation).
-
If no value is assigned to the variable being interpolated, the empty string is returned.
-
If you actually want the variable name to appear as part of the string, precede the $ by a \
- Enclose the variables name (after the $) in curly braces, or
Use the concatenation operator
-
The case-shifting string escapes (\l, \L, \u, \U) used to alter the case of letters of a string.
-
Note: A string variable preceded by a string escape is not, itself, modified.
$name = "Charles";
$age = 21;
print "$name is $age.\n"; #Charles is 21.
$name = "Amy";
$age = 18;
print "$name is $age.\n"; #Amy is 18.
print "Dollar sign \$\n"; #Dollar sign $
$what = "apple";
print "He ate two $whats.\n"; #Not correct, $whats is not known
print "He ate two ${what}s.\n"; # He ate 2 apples.
print "He ate two $what"."s.\n"; # same as above
print 'He ate two $what.\n'; #He ate two $what
Charles is 21.
Amy is 18.
Dollar sign $
Use of uninitialized valu
He ate two .
He ate two apples.
He ate two apples.
He ate two $what.\n
Standard Input and Output
- <STDIN> as a Scalar Variable
- <STDIN> is the line-input operator.
- Use <STDIN> in a place where a scalar value is expected.
-
Perl reads input from standard input (usually the keyboard) up to the first newline and uses that string as the value of <STDIN>.
-
Program stops and waits for input if nothing waiting to be read in.
-
The string value of <STDIN> typically has a newline attached – use chomp to get rid of it.
-
Printing to the Screen
-
Use print – outputs whatever follows to the standard output (usually, the screen).
$line = <STDIN>;
if($line eq "\n") {
print "That was just a blank line!\n";
} else {
print "That line of input was: $line";
}