0% found this document useful (0 votes)
44 views44 pages

Lecture Notes 14

Uploaded by

Sayan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views44 pages

Lecture Notes 14

Uploaded by

Sayan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

C/C++ Programming in a UNIX Environment

CS 3377

Bhanu Kapoor, PhD


Department of Computer Science
University of Texas, Dallas, TX
[email protected]

Lecture Notes 14

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

 Practical extraction and report language


 Similar to shell script but easier and
more powerful
 Easy availability, free
 Available for multiple OS platforms
PERL Basics
 Perl files extension .pl
 Self executing scripts
◼ First line: #!/bin/perl –w

 No compilation to create object file


 Use system commands
◼ system("unix command");
◼ system("ls *");
◼ All commands have to end in ";"

 Comments with #
PERL Basics
 Print command for writing to standard
output
◼ print “Hello, world!";
◼ Formatting with printf
◼ Close to C printing
 You can try out your first PERL program
◼ Print Hello, world! and list files in
your working directory

#!/bin/perl –w
print “Hello, world!\n";
system("ls *");
PERL Basics
 How to run a PERL program?
◼ Like shell scripts, make file executable and run
◼ $ ./helloworld.pl
◼ How do you make file executable?

◼ You can use the perl command


◼ $perl helloworld.pl

◼ You can test segments of code on the


command line with –e option
◼ $perl –e ‘print “Hello, world!” ‘
◼ $perl -e '$name="Jack" ; print "$name\n";'
6
Variables and Operations

 Scalar variables
 List variables
 Push and pop
 Shift and unshift
 Reverse and Splice
 Hash, keys, values, each
Scalar Variables
 They should always be preceded with
the $ symbol. $name = “John”;
 Not necessary to declare the variable
first and then use.
 There are no datatypes to declare.
 The scalar variable means that it can
store only one value and it can be of any
type.
 What’s difference with bash variables?
Scalar Variable
 $name = “John”;
 print "$name \n";
 The output on the screen will be John.
 Default values for all variables is undef,
equivalent to null.
Scalar Variables
 Experiment with scalar variables
 $ cat string1.pl
#!/bin/perl -w
$string="5"; # $string declared as a string, but it will not matter
print '$string+5\n'; # Perl displays $string+5 literally because of
# the single quotation marks
print "\n$string+5\n"; # Perl interpolates the value of $string as a string
# because of the double quotation marks
print $string+5, "\n"; # Lack of quotation marks causes Perl to interpret
# $string as a numeric variable and to add 5;
# the \n must appear between double quotes

10
Scalar Variables
 $ cat scalars1.pl
#!/bin/perl -w
$name = "Sam";
$n1 = 5; $n2 = 2;
print "$name $n1 $n2";
print "$n1 + $n2";
print '$name $n1 $n2';
print $n1 + $n2, " ", $n1 * $n2;
print $name + $n1;

11
List Variables
 They are like arrays. It can be considered
as a group of scalar variables.
 List variables are always preceded by the
@symbol
◼ @names = (“John",“Lisa",“James");
◼ As in C, the index starts from 0.
◼ If want the second member of the list,
you can access it as $names[1]
◼ Each element is a scalar hence $
◼ @names will give you the length of the
list i.e., 3
◼ $#names as the index of the last
element in the array named array. 12
List Variables
 $ cat arrayvar1.pl
#!/usr/bin/perl -w
@arrayvar = (8, 18, "Sam");
print $arrayvar[1]; #18
print "@arrayvar[1,2]"; #18 sam
 $ cat arrayvar2.pl
#!/usr/bin/perl -w
@arrayvar2 = ("apple", "bird", 44, "Tike",
"metal", "pike");
$num = @arrayvar2; #number of elements
print "Elements: ", $num, "\n"; #Elements: 6
13
List Variables
 $ cat arrayvar3.pl
#!/usr/bin/perl -w
$v1 = 5; $v2 = 8;
$va = "Sam"; $vb = "uel";
@arrayvar3 = ($v1, $v1 * 2, $v1 * $v2, "Max", "Zach", $va . $vb);
print $arrayvar3[2], "\n"; # one element of an array is a scalar
print @arrayvar3[2,4], "\n"; # two elements of an array are a list
print @arrayvar3[2..4], "\n"; # a slice
print "@arrayvar3[2,4]", "\n"; # a list, elements separated by SPACEs
print "@arrayvar3[2..4]", "\n"; # a slice, elements separated by SPACEs
print "@arrayvar3\n"; # an array, elements separated by SPACEs

14
Shift, Push, Pop, and Splice
 The shift function returns and removes
the first element of an array.
 The push function adds an element to
the end of an array.
 The pop function returns and removes
the last element of an array.
 The splice function replaces elements of
an array with another array.

15
Push and Pop

 @names = ("betty","veronica","tom“)

 push(@names,"lily“), now the @names


will contain
("betty","veronica","tom","lily")

 pop(@names) will return "lily" which is


the last value, @names will now
contain ("betty","veronica","tom").
Shift, Unshift, and Reverse
 Shift and unshift act on the lower
subscript.
◼ unshift(@names,"lily"), now @names contains
("lily","betty","veronica","tom").
◼ shift(@names) returns "lily" and @names
contains ("betty","veronica","tom").
 Reverse reverses the list and returns it.
◼ Reverse(@names) returns
(“tom","veronica",“betty").
Splice
 $ cat ./shift1.pl
#!/usr/bin/perl -w
@colors = ("red", "orange", "yellow", "green", "blue", "indigo", "violet");
print " Display array: @colors";
print " Display and remove first element of array: ", shift (@colors);
print " Display remaining elements of array: @colors";
push (@colors, "WHITE");
print " Add element to end of array and display: @colors";
print " Display and remove last element of array: ", pop (@colors);
print " Display remaining elements of array: @colors";
@ins = ("GRAY", "FERN");
splice (@colors, 1, 2, @ins);
print "Replace second and third elements of array: @colors";

18
Hash, keys, and values
 Hashes are like arrays but instead of
having numbers as their index they can
have any scalars as index.
 Hashes are preceded by a % symbol.
◼ We can have %hash1 = ("A",1,"B",2,"C",3);
 If we want to get the number of A we
have to print $rollnumbers{“A"}. This
will return the value of A.
Hash, Keys, and Values
 %hash1 = ("A",1,"B",2,"C",3);
 Here A is called the key and 1 is its
value.
 Keys() returns a list of all of the keys of
the given hash.
 Values() returns the list of all of the
values in a given hash.

20
Hashes
 $ cat hash1.pl
#!/usr/bin/perl -w
$hashvar1{boat} = "tuna";
$hashvar1{"number five"} = 5;
$hashvar1{4} = "fish";
@arrayhash1 = %hashvar1;
print "@arrayhash1";

21
Hashes
 $ cat hash2.pl
#!/usr/bin/perl -w
%hash2 = (
boat => "tuna",
"number five" => 5,
4 => "fish",
);
@array_keys = keys(%hash2);
say " Keys: @array_keys";
@array_values = values(%hash2);
say "Values: @array_values";

22
Each
 Each function iterates over the entire
hash returning two scalar value the first
is the key and the second is the value

%arrayvar3 = ("apple", "bird", 44, "Tike", "metal",


"pike");

while (my ($key, $value) = each %arrayvar3) {


print "$key\n";
print "$value\n";
}
Control Structures
 if/unless, if…else, if…elsif..else
 while/until
 for and foreach
 Last , next , and redo
 Use of logical operations
if/unless
 The if and unless control structures are
compound statements that have the
following syntax:
◼ if (expr) {...}
◼ unless (expr) {...}
 The if structure executes the block of
statements if expr evaluates to true;
 The unless structure executes the block
of statements unless expr evaluates to
true (i.e., if expr is false).
if/unless
 $ cat if1.pl
#!/usr/bin/perl -w
if (-r "memo1") {
print "The file 'memo1' exists and is
readable.";
}

26
if…else
 The if...else control structure is a
compound statement that is similar to
the bash if...then...else control
structure. It implements a two-way
branch using the following syntax:

if (expr) {...} else {...}

27
if…else
 $ cat ifelse.pl
#!/usr/bin/perl -w
print "Enter a number: ";
$num1 = <>;
print "Enter another, different number: ";
$num2 = <>;
if ($num1 == $num2) {
die ("Please enter two different numbers.\n");
}
if ($num1 > $num2) {
print "The first number is greater than the second number.\n";
}
else {
print "The first number is less than the second number.\n";
}

28
Comparison Operators

29
if…elsif…else
 Similar to the bash if...then...elif control
structure, the Perl if...elsif...else control
structure is a compound statement that
implements a nested set of if...else
structures using the following syntax:

if (expr) {...} elsif {...} ... else {...}

30
if…elsif…if
 Rewrite previous example using elsif
if ($num1 > $num2) {
print "The first number is greater than the
second number.\n";
}
elsif ($num1 < $num2) {
print "The first number is less than the second
number.\n";
}
else {
print "Please enter two different numbers.\n";
}

31
foreach/for
 This statement takes a list of values and
assigns them one at a time to a scalar
variable, executing a block of code with
each successive assignment.
◼ foreach/for $var (list) {}
 $ cat foreach.pl
foreach $item ("Mo", "Larry", "Curly") {
print "$item says hello.";
}
If you do not specify var, Perl assigns
values to the $_ variable
foreach/for
 $ cat foreacha.pl
foreach ("Mo", "Larry", "Curly") {
print "$_ says hello.";
}
 foreach and for are synonyms
 The second syntax for the foreach
structure is similar to the C for
structure:
foreach|for (expr1;expr2;expr3) {...}

33
foreach/for
 $ cat ./foreach2.pl
#!/usr/bin/perl -w
print "Enter starting number: ";
$start = <>;
print "Enter ending number: ";
$end = <>;
print "Enter increment: ";
$incr = <>;
if ($start >= $end || $incr < 1) {
die ("The starting number must be less than the ending
number\n",
"and the increment must be greater than zero.\n");
}

foreach ($count = $start+0; $count <= $end; $count += $incr) {


print "$count";
}
34
while/until
 The while and until control structures
are compound statements that
implement conditional loops using the
following syntax:

while (expr) {...}


until (expr) {...}
while/until
 $ cat while1.pl
#!/usr/bin/perl -w
$count = 0;
while ($line = <>) {
print ++$count, ". $line";
}
print "\n$count lines entered.\n";
------
while (my $line = <>) {
chomp $line;
if ($line =~ /regex/) ...
} 36
last/next/redo
 Last is similar to break statement of C.
 To skip the current loop iteration use the
next statement.
 The redo statement helps in repeating
the same iteration again.
 $ cat foreach1.pl
foreach $item ("one", "two", "three") {
if ($item eq "two") {
next;
}
print "$item";
}
Read/Write to Files
 To read and write to files we create
something called handles which refer to
the files.
 To create the handles we use the open
command.
◼ open(filehandle1,"filename");
◼ This handle will be used for reading.
◼ open (file-handle, ['mode',] "file-ref");
◼ open(filehandle2,">>filename");
◼ Specify mode as > to truncate and write to
a file or as >> to append to a file.
Read / Write to Files
 Once the file handles have been
obtained, the reading and writing to files
is simple.
◼ $linevalue = <FILEHANDLE1> ;
 This will result in a line being read from
the file pointed by the filehandle and the
that line is stored in the scalar variable
$linevalue.
 For closing a filehandle use
close(FILEHANDLE);
Read/Write Files
 $ cat file2.pl
open (my $infile, "/usr/share/dict/words") or
die "Cannot open dictionary: $!\n";
while ($line = <$infile>) {
print $line;
}

40
PERL Random Numbers
 Between 0 and 1
#!/bin/perl
$random_num = rand();
print $random_num "\n";

 Between 0 and 100


#!/bin/perl
$max = 100
$random_num = int(rand($max));
print $random_num "\n";

41
PERL random numbers
 Between any two numbers
#!/bin/perl
$min = 50
$max = 100
$random_num = int(rand($max -$min)) + $min;
print $random_num "\n";

42
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.

43
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";

44

You might also like