Engineering Foundations of Robotics

Download as pdf or txt
Download as pdf or txt
You are on page 1of 70

UNIT-5

Advanced PERL

S.Nagaleela
Asst Professor
ECE
Patterns and Regular expressions(regex)
• Regular expressions provide an extremely powerful way of defining patterns
• It is a notation for describing the strings produced by a regular grammar
• Regular expressions will make the program simpler
E.g. program to search for a word in the array

$f=0;
$_=“hello good morning everybody”;
$s=“every”;
If($s eq $_)
{
$f=1;
last;
}
If($f)
Print “found the word $s\n”;
Else
Print(‘not found\n”);
• Using regex

$_=“hello good morning everybody”;


if($_=~/every/)
{ found the word “every”\n);}

• the text between forward slashes defines the regular expression


• /^cat/ matches the string cat only if cat matches the string cat
E.g.
$_="cathello good morning everybody";
if($_=/^cat/)
{print ("found the word 'cat'\n")}
Else
{ print ("not found\n")}
• /cat$/ matches only at the end of a line
• dot (.) matches any character except new line so /c.t/ matches cat,
cot, cut, etc. E.g.
$string="hello cat good morning every bodyss";
if ($string=~/c.t/) # /c..t/ will search for two letters
{print "match found/n";}
else{ print "no match"};
• The character class is a set of characters enclosed in square brackets,
matches any single character from the listed
E.g. /[aeiou] / matches any vowel, /[0123456789]/matches any digit
• A character class of the form /[^…]/ matches any character except
those listed, so / [^0 - 9] matches any non-digit

E.g.
$string="hello cat good morning every15376 bodyss";
if ($string=~/[0-9]/)
{print "match found/n";}
else{ print "no match"};
E.g.
$string="476";
if ($string=~/[^0-9]/)
{print "found non-digit character\n"}
else{ print "no non-digit character\n"}
E.g.
$str="howarethedays ";
if($str=~/\w\w\w\s/)
{ print("found a three letter word")}
else
{print("not found")}
E.g. anchors
$str="how are good thedays";
if($str=~/^\w/)
{ print("found a letter at the beginning\n");}
if($str=~/\w$/)
{print("found a letter at the end\n");}
if($str=~/\bgood\b/)
{print("found the word 'good'\n ");}
Multipliers
• Repetition of characters within a regular expression can be specified
by quantifiers
*(zero or more occurrences), + (one or more occurrences)
? (zero or one occurrence)
E.g.
$str=~/^\w+/;
$str=~/\d?/;
$str=~/\w+\s?$/;
$str=~/\b\w+\s+/;
Substitution
• specify a substitution to be made when a match succeeds
• Uses the character ‘s’
Syntax:
$new=~s/pattern_to_match/new_pattern/;
• It looks for the pattern and replaces it with new one
• Only first occurrence is replaced
E.g.
$str="rama and rani went to college";
$str=~s/rama/radha/;
print "$str\n";
$str=~s/r\w+a/radhika/;
print "$str\n";
$str=~s/[aeiou]/i/;
print "$str\n";
Common modifiers
/i---ignore case
/g---match/substitute all occurrences

E.g.
$str="rAma and rani went to college";
$str=~s/RAMA/radha/i;
print "$str\n";
E.g.
$str="rAma and rani went to college";
$str=~s/a/s/g;
print "$str\n";
$str="rAma and rani went to college";$str=~s/a/s/gi;print
"$str\n"; # ignore-case and allmatches
Use of memory in regex
• Use parenthesis to capture the piece of matched text for later usage
• Captured text can be recalled
---use $1,$2,$3,….. after Regex

E.g.
$str= 'rani radha went to college';
$str=~/(\w+)\s(c\w+)/;
print "$1\n$2";
Special variables
• $&---specifies the present match (part of the string that matched)
• $`---specifies the value previous to the match(part of the string before
the part that matched)
• $'---specifies the value after the match (part of the string after the
part that matched)

E.g. $_ = "this is a sample string";


$str= 'helloworld’; $_=~/sa.*le/;
$str=~/llow/; print "$`\n$&\n$'\n";
print "$`:$& :$'\n"; # he:llow:rld
Eg. PERL script to search for the given word from the given string which
will take runtime input word to search for

$sentence = "Every good bird does fly.";


print "What should I look for? ";
$what = <STDIN>;
chomp($what);
if ($sentence =~ /$what/) # found it!
print {"I saw $what in /n $sentence.\n";}
else
{ print "nope... didn't find it.\n";}
split and join Functions
split
• takes a regular expression and a string, and looks for all occurrences
of the regular expression within that string
• The parts of the string that don't match the regular expression are
returned in sequence as a list of values
• Eg. Using split function
$line = "merlyn::118:10:Randal:/home/merlyn:/usr/bin/perl";
@fields = split(/:/,$line); # split $line, using : as delimiter
foreach (@fields)
{print "$_\n"}
join Function
• The join function takes a list of values and glues them together with a
glue string between each list element

Eg:
$outline = join(":", @fields);
Subroutines
• Subroutines (subs) are named blocks of code
• A Perl subroutine or function is a group of statements that together performs a
task
• divide the code into separate subroutines
Definition of a Subroutine
• The general form of a subroutine definition in Perl programming language is as
follows −
sub subroutine_name
{ body of the subroutine }
Calling a subroutine
subroutine_name( list of arguments );

E.g.
sub Hello # Function definition
{
print "Hello, World!\n";
}
Hello(); # Function call
Passing Arguments to a Subroutine
• You can pass various arguments to a subroutine like you do in any other
programming language
• These can be accessed inside the function using the special array @_.
• the first argument to the function is in $_[0], the second is in $_[1],...
E.g.
sub Average
{
$n = @_ ; # get total number of arguments passed
$sum = 0;
foreach $x (@_)
{ $sum += $x; }
$average = $sum / $n;
print "Average for the given numbers : $average\n";}
Average(10,20,90);
Passing Lists to Subroutines
• @_ variable is an array, it can be used to supply lists to a subroutine
• If you have to pass a list along with other scalar arguments, then make list
as the last argument

E.g.
sub PrintList
{
@list = @ _;
print "Given list is @list\n"; }
$ a = 10;
@ b = (1, 2, 3, 4);
PrintList($a,@b); # Function call with list
Passing Hashes to Subroutines
• When you supply a hash to a subroutine that accepts a list, then hash
is automatically translated into a list of key/value pairs

E.g.
sub PrintHash # Function definition
{ %h = @_;
foreach $key ( keys %h )
{ $value = $h{$key};
print "$key : $value\n"; }
}
%hash = ('name' => 'Tom', 'age' => 19);
PrintHash(%hash); ; # Function call with hash parameter
Returning Value from a Subroutine
• You can return a value from subroutine like you do in any other
programming language
• If you are not returning a value from a subroutine then whatever
calculation is last performed in a subroutine is automatically the
return value
• You can return arrays and hashes from the subroutine like any scalar
• returning more than one array or hash normally causes them to lose
their separate identities
E.g.
sub Average
{
$n = @_; # get total number of arguments passed
$sum = 0;
foreach $item (@_)
{ $sum += $item; }
$average = $sum / $n;
return $average; }
$num = Average(10, 20, 30); # Function call
print "Average for the given numbers : $num\n";
Pack and Unpack
Pack
• The pack function resembles join and it combines a list of items into a
string
• builds a structure described by a template which is as an argument,
and returns this as a string
• Both of the functions take, as their first argument, a string of
characters which describe the format of the data to be packed or
unpacked
• The pack function takes a list of values to be packed as a second
argument and returns a scalar character string containing the packed
values.
Unpack
• The unpack function reverses the process, a string representing a data
structure into a list
• The unpack function takes a character string containing the values to
be unpacked as a second argument, and returns a list of individual
values extracted from the string
Example:
pack “cccccccccc" , @codes
or
pack "c10”, @codes
or
$count = @codes;
pack "c$count" , @codes;
working with files
• A filehandle is a named internal Perl structure that associates a
physical file with a name
• All filehandles are capable of read/write access, so you can read from
and update any file or device associated with a filehandle
• However, when you associate a filehandle, you can specify the mode
in which the filehandle is opened
• Three basic file handles are - STDIN, STDOUT, and STDERR, which
represent standard input, standard output and standard error devices
respectively
File Handling
• A filehandle is a structure allows functions in perl to interact with a file.
• A filehandle is an abstract name given to a file, device, socket or pipe.
• A filehandle helps in getting input from and sending output to many
different places.
• To create a filehandle using the open command with following arguments;
• The name of the filehandle (all in uppercase by convention)
• The mode of the filehandle (read, write or append)
• The path to the file

33
File Handling
• When selecting a mode for your filehandle perl uses the symbols;
• < for a read-only
• > for a writable
• >> for an append
• Examples:
open (IN,‘< C:/readme.txt');
open (OUT,'>>C:/writeme.txt');
open (OUT,'>','C:/writeme.txt');
open (OUT,'>C:/writeme.txt');

• Close the file handle with CLOSE Function


• Example : close(IN); close(OUT);
File Handling
• Reading from a file
• To read data from a file you use the <> operator.
$file = “C:/tale_of_two_cities.txt";
open (IN, $file) or die "Can't read $file: $!";
$first_line = <IN>;
print $first_line;
print "The end";
File Handling
$file = “C:/tale_of_two_cities.txt";
open (IN,$file) or die "Can't read $file: $!";
$first_line = <IN>;
chomp $first_line;
print $first_line;
print "The end";
File Handling
$file = “C:/tale_of_two_cities.txt";
open (IN,$file) or die "Can't read
$file: $!";
$line_count = 1;
while (<IN>)
{
chomp;
print "$line_count: $_\n";
last if $line_count == 5;
++$line_count;
}
File Handling
• Example:

• # open file for reading


• open(my $input_fh, "<", $filename) or die $!;
• # open file for writing
• open(my $output_fh, ">", $filename) or die $!;
• # copy file
• my $line_no = 1;
• while(<$input_fh>) {
• print $output_fh "$line_no: $_";
• $line_no++;
• }
File Handling
• Writing to a file
• Writing to a file is really simple. The only function you
need to use is print
File Handling
• Example:
# open file for reading
open(IN, "<", $filename) or die $!;
# open file for writing
open(OUT, ">", $filename) or die $!;
# add line numbers to each line
$line_no = 1;
while(<IN>)
{
print OUT "$line_no: $_";
$line_no++;
}
Testing files (File Status Checks)
• allow us to find out basic information about a file.
• The file test operators are:
• -e : Tests if a file exists
• -r : Tests if a file is readable
• -w : Tests if a file is writable
• -d : Tests if a file is a directory
• -f : Tests if a file is a file
• -T : Tests if a file is a plain text file
Testing files (File Status Checks)

if (-r $file) {
print "$file is readable\n";
}
elsif (! -w $file) {
print "$file is write protected\n";
}
}
Type globs
• Generic Variable Name which produces a scalar varaible that represents all the
variables of that name

• Example: *vnr can represent $vnr @vnr %vnr and &vnr

• Symbol Table resembles hash where key is the identifier and associated value
consists slots for each of the thing that share same name.

• We can perform the operations like: Assign the value to a variable, Store in an array,
Pass it as parameter to a subroutine.

• Typeglobs Assignment : *b = *vnr; #b is an alias for vnr


Type globs and filehandles

$INFILE = “test.txt”;
Open INFILE
&Fileop (*INFILE);

Sub fileop
{
local *FILE = shift
While (<FILE>) {
.............;
}
References
• A reference is a scalar value and can refer to any other Perl data type and
can be used in any context that a scalar is valid.
• More complex data types can be constructed using references, which allow
you to build lists and hashes within lists and hashes.

• Allowing indirect access to a piece of data - the value of a pointer variable


tells us where we will find the data object.

• A Perl variable is an association of an identifier in the symbol table with a


reference to a value.
Hard reference: which locates an actual value in memory.

Symbolic reference: which is a variable whose value is a string that happens to be the
name of another variable.

• The only operation that can be carried out on a reference is dereferencing, i.e. locating
the referent.

• If the identifier appears in an expression, dereferencing takes place to obtain the value:

• If it occurs on the left-hand side of an assignment, the reference is used to locate the
value to be updated.
Creating references
• To create a reference to a variable or subroutine, you use the
unary backslash operator (\) in front of the variable or
subroutine name
E.g.
$sref = \$foo;
$aref = \@ARGV;
$href = \%ENV;
$coderef = \&handler;
$globref = \*foo;
References to anonymous values
• An anonymous scalar is just a constant, and it is possible to create a
reference to it

E.g.
$pi_ref = \3.145926536;
$ref2array = \[255, 127, 0];
$ref2array2 = \[255, 127, 0, [255, 255, 255]];
$ref2hash = \{winter => 'cold', summer => 'hot‘} ;
$ref2sub =\ sub{ ... };
Dereferencing
• The operation of dereferencing applied to a reference delivers the
referent
• Dereferencing returns the value from a reference point to the location

E.g.
$var1 = 10;
$r1 = \$var1;
print "Value of $var1 is : $$r1\n";
@var2 = (1, 2, 3);
$r2 = \@var2;
print "Value of @var2 is : ", @$r2, "\n";
%var3 = ('key1' => 10, 'key2' => 20);
$r3 = \%var3;
print "Value of %var3 is : ", %$r3, "\n";
Perl array references
• To refer each element of the array use $ar->[0], $ar->[1]…
Or ${$ar}[0], ${$ar}[1]...

E.g.
@a = (1..5);
$ar = \@a;
$i = 0;
foreach(@$ar)
{print("${$ar}[$i++] \n");
}
Perl hash references

E.g.
%months= ( Jan => 1,Feb => 2,Mar => 3);
$mr=\%months;
foreach(keys %$mr)
{print "$_ =>$$mr{$_}\n "}
• If you are not sure about a variable type, then its easy to know its
type using ref
• it returns type of the argument with reference. Otherwise returns
false
Eg.
$var1 = 10;
$r1 = \$var1;
print "Reference type in r1 : ", ref($r1),"\n";
@var2 = (1, 2, 3);
$r2 = \@var2;
print "Reference type in r2 : ", ref($r2), "\n";
%var3 = ('key1' => 10, 'key2' => 20);
$r3 = \%var3;
print "Reference type in r3 : ", ref($r3), "\n";
eval
• The eval operator comes in two forms
In its first form it takes an arbitrary string as an argument and evaluates the at run-time, as
a Perl script.
The second form evaluates BLOCK
• It takes a block as Its argument and the block will compiled only once as the same time
of remaining code.
• Places the error message in the variable $@.
• If there is no error, the value of $@ is an empty string .
• These provides a robust exception handling mechanism.
Syntax:
eval EXPR
eval BLOCK E.g. block evaluation
eval
{ ....... #code which might
E.g. expression evaluation have errors
$str = '$a++; $a + $b'; # Contains two }
expressions If($@ ne “ ”)
{ ........ # cleanup after error
$a = 10; $b = 20;
}
$c = eval $str;
print "$c“;
Data structures
Arrays of Arrays
• In perl a two dimensional array is constructed by creating an array of references
to anonymous arrays
• The array composer converts each comma-separated list to an anonymous array
in memory and returns a reference and when we write an exp
E.g.
@colors = ( [35,39,43] , [4,5,8] , [32,31,25] ) ;
$colors [0][2] = 43;
• $colors [0] is a reference to an array and 2nd subscript represents the element
present in that array.
E.g.
@ar=([0,1,2],[3,4,5],[6,7,8]);
$r=$ar[1][2];
print "value:$r";
Complex Data Structures
• Not only an array of arrays can be created but we can create hashes
of hashes ,arrays of hashes and hashes of arrays
• By combining all these possibilities ,data structures of great
complexity can be created
ex: doubly linked list
Packages
• A package is a collection of code which lives in its own namespace
• Syntax: package package_name
• A namespace is a named collection of unique variable names (also
called a symbol table), Which determines bindings of names both at
compile-time and run-time.
• Namespaces prevent variable name collisions between packages
• Package statement switches the current naming context to a
specified namespace (symbol table)
• If the named package does not exists, a new namespace is first
created.
• The package stays in effect until either another package statement is
invoked, or until the end of the current block or file.
• You can explicitly refer to variables within a package using the ::
package qualifier

• Initially, code runs in the default package main. Variables used in a


package are global to that package but invisible in any other
package unless a 'fully qualified name' is used
• $A: : x is the variable x in package A,
• $B: : x is the (different) variable x in package B
• $x is the variable x in the package main.
• A package is introduced by the package declaration, and extends to
the end of the innermost enclosing block, or until another package
declaration is encountered.
• In this case the original package declaration is temporarily hidden
E.g.
$i = 1;
print "$i\n"; # Prints "1"

package A;
$i = 2;
print "$i\n"; # Prints "2"

package main;
print "$i\n"; # Prints "1"
print "$A::i\n"; # Prints "2"
E.g.
# This is main package
$i = 1;
print "package name :",__PACKAGE__ , " $i\n";

package Foo; # This is Foo package


$i = 10;
print "Package name : " , __PACKAGE__ , " $i\n";

package main; # This is again main package


$i = 100;
print "Package name : " , __PACKAGE__ , " $i\n";
print "Package name : " , __PACKAGE__ , " $Foo::i\n";
Libraries and modules
• Libraries and modules are packages contained within a single file, and
are units of program reusability.
• The power of Perl is immensely enhanced by the existence of a large
number of publicly available libraries and modules that provide
functionality in specific application areas.
Libraries
• A library is a package that contains a collection of related subroutines
that can be used in some specific purpose.
• A library is usually declared as a package to give it a private
namespace, and is stored in a separate file with an extension .pl
• If we have a library of mathematical functions in a library stored in a
file math.pl.
• These subroutines can be loaded into a program by placing the
statement
require “math.pl”; at the head of the program
• If the library is declared as a package called math, we can call its
functions using fully qualified names
e.g. $rootx=math: : sqrt ($x) ;
Modules
• A Perl module is a reusable package defined in a library file whose
name is the same as the name of the package with a .pm as
extension.
• the great thing about a module is that the names of the subroutines
in the module are automatically imported into the namespace of the
program using the package.
E.g. the collection of mathematical routines in the library math.pI are
converted into a module math.pm,
• The functions require and use will load a module
• The module names are imported by calling the import() method
defined in the module
Use math;

BEGIN
{
require “math.pm”;
math::import();
}
• A user can also import only selected subroutines of a module.
Use math(‘sqrt’, ‘sin’, ‘cos’);

BEGIN
{
require “math.pm”;
math::import (‘sqrt’, ‘sin’, ‘cos’);
}
Objects
• An object is an anonymous data structure that is accessed by a
reference, has been assigned to a class, and knows what class it
belongs to.
• Classes: A class is a package that provides methods to deal with
objects that belong to it. There is no special syntax for class definition.
• Constructors: constructor is just a subroutine that returns a
reference to an object.
• The object is said to be blessed into a class by calling the built-in
function bless in a constructor.
• Methods: Finally, a method is a subroutine that expects an object
reference as its first argument (or a package name for class methods).

• An object is just a chunk of referenced data, but the blessing


operation ties it to a package that provides the methods to
manipulate that data.
Creating Object using Constructor
• Objects are created by a constructor subroutine which is generally
called new Example:
package Animal;
sub new {
my $ref = {};
bless ref;
return ref;
}

package Animal;
sub new {return bless {};
}
Instances
• With this constructor new defined we can create instances of the
object (strictly speaking. references to instances)
$Dougal = new Animal;
$ Ermyntrude = new Animal;
• This makes $Dougal and $Ermyntrude references to objects that are
empty hashes, and 'know' that they belong to the class Animal.
• Note that although the right-hand side of the assignment, new
Animal, looks superficially like a simple call of a subroutine new
with one argument Animal, it is in fact a special syntax for calling
the subroutine new in the package Animal.

You might also like