Engineering Foundations of Robotics
Engineering Foundations of Robotics
Engineering Foundations of Robotics
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
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)
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');
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
• 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.
$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.
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
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";
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).
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.