Lecture Notes 15
Lecture Notes 15
CS 3377
Lecture Notes 15
1
Reading for Week 13-14
Chapter 11 of A Practical Guide to
Linux® Commands, Editors, and Shell
Programming, Third Edition. Mark G.
Sobell.
◼ Chapter 11: The Perl Scripting Language
2
PERL Random Numbers
Between 0 and 1
#!/bin/perl
$random_num = rand();
print $random_num "\n";
3
PERL random numbers
Between any two numbers
#!/bin/perl
$min = 50
$max = 100
$random_num = int(rand($max -$min)) + $min;
print $random_num "\n";
4
PERL User Inputs and Chomp
The chomp() function will remove (usually)
any newline character from the end of a
string.
#!/bin/perl
while (my $text = <STDIN>)
{ chomp($text);
print "You entered '$text'\n";
last if ($text eq '');
}
If you chomp an array, it will remove a newline
from the end of every element in the array.
5
Opening and Writing to a File
open(my $fh, '>>', 'report.txt');
Opens the file report.txt in the working
directory in append mode.
$fh is the file handle for this file
print $fh “Hello, world\n";
6
Variable Types
Scalar
◼ $num = 14;
◼ $fullname = “John H. Smith”;
◼ Variable Names are Case Sensitive
◼ Underlines Allowed: $Program_Version =
1.0;
Usage of scalars
◼ print ("pi is equal to: $pi\n");
◼ print "pi is still equal to: ", $pi, "\n";
◼ $c = $a + $b;
Variable Types
A scalar variable can be "used" before it
is first assigned a value
◼ Result depends on context
◼ Either a blank string ("") or a zero (0)
◼ It can be source of subtle bugs in your code
◼ For example, if a variable name is mispelled
then what value should it get?
◼ Good idea to use –w opition
8
Variable Types
Arithmetic
◼ Basic operators: + - * / %
◼ $total = $subtotal * (1 + $tax / 100.0);
◼ Exponentiation: **
◼ $cube = $value ** 3;
◼ $cuberoot = $value ** (1.0/3);
◼ Bit-level Operations
◼ left-shift: << $val = $bits << 1;
◼ right-shift: >> $val = $bits >> 8;
Operators
Assignments
◼ Includes: = += -= *= /= **= <<=
>>=
◼ $value *= 5;
◼ $longword <<= 16;
◼ Increment: ++
◼ $counter++ ++$counter
◼ Decrement: --
◼ $num_tries-- --$num_tries
Operators
Boolean Assignment
◼ &= |= ^=
◼ $picture &= $mask;
Logical (Expressions)
◼ && And operator
◼ || Or operator
◼ ! Not operator
Operators
expr1 || expr2
◼ expr1 is evaluated.
◼ expr2 is only evaluated if expr1 was false.
Examples
◼ open (…) || die “couldn’t open file”;
◼ $debug && print “user’s name is $name\n”;
Operators
◼ Modulo: %
◼ $a = 123 % 10; ($a is 3)
◼ Multiplier: x
◼ print “ride on the ”, “choo-”x2, “train”;
(prints “ride on the choo-choo-train”)
◼ $stars = “*” x 80;
◼ Assignment: %= x=
Operators
◼ String Concatenation: . .=
◼ $name = “Uncle” . “ “. “Sam”;
◼ $cost = 34.99;
◼ $price = “Hope Diamond, now only \$”;
◼ $price .= “$cost”;
Conditionals
numeric string
◼ Equal: == eq
◼ Less/Greater Than: < > lt gt
◼ Less/Greater or equal: <= >= le ge
◼ Zero and empty-string means False else True
◼ Comparison: <=> cmp
◼ Results in a value of -1, 0, or 1
◼ Logical Not: !
◼ if (! $done) {
print “keep going”;
}
Conditionals
#!/bin/perl –w
$a = "123";
$b = "1234";
$c = "124";
if ($b gt $c) {
print "$b gt $c\n";
} else {
print "$b le $c\n";
}
18
Control Structures
“while” loop
◼ while (condition) { code }
◼ $cars = 7;
while ($cars > 0) {
print “cars left: ”, $cars--, “\n”;
}
◼ while ($game_not_over) {…}
Control Structures
Bottom-check Loops
◼ do { code } while (condition);
◼ do { code } until (condition);
◼ $value = 0;
do {
print “Enter Value: ”;
$value = <STDIN>;
} until ($value > 0);
No Switch Statement
$foo = 10;
{
my $foo = 3;
print $foo; #prints 3
}
print $foo; #prints 10
Where’s the scope
Subroutines declared within a lexical’s
scope have access to that lexical
Like implementing static variables in Perl
{
my $num = 20;
sub add_to_num { $num++ }
sub print_num { print “num = num\n”; }
}
add_to_num;
print_num;
print $num; #ERROR!
local
local does not create new variable
assigns temporary value to an existing (global)
variable
has dynamic scope, rather than lexical
functions called from within scope of local
variable get the temporary value
sub fctn { print “a = $a, b = $b\n”; };
$a = 10; $b = 20;
{
local $a = 1;
my $b = 2;
fctn();
}
#prints a = 1, b = 20
What to know about scope
my is statically (lexically) scoped
◼ look at code. whatever block encloses my is
the scope of the variable
local is dynamically scoped
◼ scope is enclosing block, plus subroutines
called from within that block
Almost always want my instead of local
◼ notable exception: cannot create lexical
variables such as $_. Only ‘normal’, alpha-
numeric variables
◼ for built-in variables, localize them.
Prototypes
Perl’s way of letting you limit how you’ll
allow your subroutine to be called.
when defining the function, give it the
‘type’ of variable you want it to take:
sub f1 ($$) {…}
◼ f1 must take two scalars
sub f2($@) {…}
◼ f2 takes a scalar, followed by a list
sub f3(\@$) {…}
◼ f3 takes an actual array, followed by a
scalar
Prototype Conversions
sub fctn($$) { … }
fctn(@foo, $bar)
Perl converts @foo to scalar (ie, takes
its size), and passes that into the
function
sub fctn2(\@$) {…}
fctn2(@foo, $bar)
Perl automatically creates reference to
@foo to pass as first member of @_
Prototype generalities
while (<STDIN>) {
if (/abc/) {
print “>> found ‘abc’ in $_\n”;
}
}
Combine metacharacters
/a.{4}c/ => ‘a’ followed 4 instances of any
character followed by ‘c’
so will match addddc , afgthc , ab569c,etc.