Вы находитесь на странице: 1из 37

P a g e |0

USE OF PERL IN DESIGN FLOW AUTOMATION


AND TESTING IN VLSI
By,
Vicky Dhudashia (SJSU ID: 009428705)

Under the Guidance of Date Signature


Dr. Morris Jones 10 Dec 2014

Page | 0
Objective

The purpose of this paper is to explain how one can write a PERL program to automate
compilation, simulation and synthesis and report generation with pointing out errors and
important details as per user demand. This paper is a head start for those students, who want to
learn PERL to automate tasks in HDL design compilation to synthesis. For the last comprehensive
example, it is assumed that the user is familiar with UNIX operating system and already have VCS,
DC Shell, and GTKWave in the computer system.
In VLSI, (Very Large Scale Integration) design while doing a compilation, simulation and synthesis,
after passing every stage, the user has to give commands with Verilog files and test bench
containing the dump file declaration. After that, every time, the user has to wait for passing this
stage or expecting error in execution. If the design passes one stage than another command for
the next stage is given. After synthesis, netlist file as a result contains cells listed from the library
file specified in synthesis script. This synthesis is done using NCVerilog of cadence. Then the user
has to extract manually all the reports to search for desired value. If this process is being done in
development and testing, then it becomes very hectic for user to enter the same command every
time because, this may have to be followed until successful passing of design.
So instead of doing these operations manually, PERL script is being written and it takes care of all
things from error detection in report to data extraction.
By, the end of this paper one complete example will be shown that will operate on Verilog code,
and will do all the operations, according to specifications.
In this paper, every type of special word is indicated with a different color so, the reader can
easily identify and differentiate between variable, array, hashes, comment, and subroutine.

Page | 1
Table of Contents
Objective ........................................................................................................................................................................1
Introduction: ..................................................................................................................................................................5
PERL and its application .............................................................................................................................................5
Why PERL over other scripting languages? ...............................................................................................................5
Installation of PERL in Linux ...........................................................................................................................................6
Installation of PERL Modules .........................................................................................................................................6
Execution of PERL ..........................................................................................................................................................7
Useful syntax structure in PERL .....................................................................................................................................7
Comments..................................................................................................................................................................7
Switches .....................................................................................................................................................................8
-e ............................................................................................................................................................................8
-n ............................................................................................................................................................................8
-c ............................................................................................................................................................................8
Reading from a Pipe...................................................................................................................................................8
Difference between single quote ’ and double quote ” ................................................................................................9
Variables in PERL ...........................................................................................................................................................9
Scalars: .......................................................................................................................................................................9
Declaration of scalars ..........................................................................................................................................10
Expression with Scalars........................................................................................................................................10
Use of auto increment .....................................................................................................................................10
Use of auto decrement ....................................................................................................................................10
String Concatenation ...........................................................................................................................................10
Arrays .......................................................................................................................................................................11
Declaration of an Array ....................................................................................................................................11
Element declaration in an Array ......................................................................................................................11
shift ..................................................................................................................................................................12
unshift ..............................................................................................................................................................12
use of single and double quotes variation in print statement.........................................................................12
pop ...................................................................................................................................................................13
Push .................................................................................................................................................................13
Alphabetic sort.................................................................................................................................................13
Numerical sort .................................................................................................................................................13
Result: ..............................................................................................................................................................13
Hashes .....................................................................................................................................................................14

Page | 2
Declaration of hashes ..........................................................................................................................................14
Conversion from normal array to hash array and from hash array to normal array ...........................................15
Accessing value ................................................................................................................................................15
Subroutine ...............................................................................................................................................................16
Call by reference ..................................................................................................................................................16
Call by value .........................................................................................................................................................17
File Handling ................................................................................................................................................................17
STDIN --- Standard Input ..........................................................................................................................................17
Without using chomp ......................................................................................................................................17
using chomp.....................................................................................................................................................18
File Operation in PERL .................................................................................................................................................18
Default variables in PERL .........................................................................................................................................18
Open ........................................................................................................................................................................19
close .........................................................................................................................................................................19
Write ........................................................................................................................................................................19
Append ....................................................................................................................................................................19
Command line arguments ...........................................................................................................................................20
ARGV, <ARGV> and <AEGV> ....................................................................................................................................20
Control Structures in PERL ...........................................................................................................................................21
If... else ....................................................................................................................................................................21
While........................................................................................................................................................................22
For ............................................................................................................................................................................23
Foreach ....................................................................................................................................................................23
Breaking out of loop ................................................................................................................................................23
Skipping to end of loop ............................................................................................................................................24
Split function............................................................................................................................................................24
Regular Expression ......................................................................................................................................................24
Without RegEx: ........................................................................................................................................................24
Split function........................................................................................................................................................25
Using RegEx .............................................................................................................................................................25
Matching ..................................................................................................................................................................25
Substitution .............................................................................................................................................................25
Character Class ........................................................................................................................................................26
Substitution .................................................................................................................................................................27
Memory in PERL.......................................................................................................................................................27

Page | 3
Useful functions for User interaction ..........................................................................................................................28
Read .........................................................................................................................................................................28
die ............................................................................................................................................................................29
do .............................................................................................................................................................................29
exit ...........................................................................................................................................................................29
grep ..........................................................................................................................................................................29
Verilog Design ..............................................................................................................................................................30
Verilog Test Bench .......................................................................................................................................................32
PERL Script ...................................................................................................................................................................34
Conclusion ...................................................................................................................................................................36

Page | 4
Introduction:

PERL and its application


Practical Report and Extraction Language (PERL) is one of the most used from available scripting
languages because of its simple syntax structure and strong text manipulation with excellent data
interface capability. It is widely popular and used for its strong string handling capability. It is an
interpreted language. PERL can be optimized for searching any text files, for numeric or
alphabetic information, extracting that information from file and generating reports from
different format of files. PERL has its inbuilt functions that can be used for string shortening with
respect to alphabet as well as numerical order and other functions like reverse, split, grep and
many more. It is very useful in web development and also known as a server side programming
language because, it does not run directly on the client end, i.e. Web browser, mobile device, etc.
Being a server side programming language, it is used to implement the business logic. So upon a
request from a client, it performs all the server side computation and also handles all the
operation of connecting database and other services and in response provide a result in a form
that can be represented at the client end.
It is a procedural and high level language. PERL is mainly used in, web development and
automating tasks to save human effort and time to do repeated the same function. PERL is
interpreted so every time after updating PERL program user does not need to compile programs.
This is mainly used in automating tasks in development and testing. Where all commands are
written in a single file and then, it is executed. Moreover, PERL’s regular expressions (REGEX)
known as REGEX are very helpful in matching and substituting text values in the file. It is used
with delimiters to determine which value is to be matched. This is the main advantage in string
handling capability.
Why PERL over other scripting languages?
PERL is supported on every platform. It is free so it does not need to purchase. Flexibility is also
an important feature. It does not limit on the size of data. Even 60mb of file, entire file containing
text can be assigned to a single string variable.
After reading these specifications, one question surely comes in mind that, there are many other
scripting languages but why PERL over those languages?
There is no absolute answer. Every language has its own pros and cones. The reason why PERL is
easy to use over Python is, Python is indented language. In Python, indentation matters a lot, so
If, the code is not written with correct indentation, then it does not execute as desired. The
biggest advantage in PERL is indentation does not matter because of the way syntax is used. PERL
is an oldest scripting language been used over many years and it is very easy to use with Linux
and UNIX operating systems.

Page | 5
Installation of PERL in Linux

1) Go to https://www.perl.org/get.html, Then Download relevant version according to


computer system being used.
2) Run downloaded file. This will extract modules itself and after restart, it will install PERL.
3) Now it is ready to use. Just have to write in console PERL followed by the file to be
executed.
.pl is the file extension for PERL script file.
Always before going into learning a new language, it is better to show how to use it by using
a simple print command.

Installation of PERL Modules

PERL has built in modules that are very useful in general programming, file handling, error
handling, text processing, CGI applications, database interface, networking, and language
extension. These are highly optimized algorithms to provide uniqueness and at some point of
view security to the database. For downloading, follow the steps explained below:
1) Go to http://www.cpan.org/modules/index.html. Here all modules are listed according to
the category.
2) Packages of the module Verilog-Perl is useful is used in this paper.
3) Select modules needed and then go to http://www.cpan.org/modules/INSTALL.html.
There is detailed instructions for installing these modules.

Page | 6
Execution of PERL

PERL file execution can be done in two ways. Extension of PERL file is .pl
1) Direct execution from command line.

perl print "Good Luck\n";

Here perl indicates PERL interpreter being used to execute the file written after or to
execute commands written after it.
Good Luck

2) If the PERL file is being used for automation then, whole script can be written in the text
editor with .pl extension. Now by just mentioning this file name in konsole with PERL
command it can be executed.
Open a simple text file,
Provide PERL executor’s path name: in general, it is like: #!/usr/bin/perl
Here #! Indicates that this current file is to be executed from the application named PERL
being saved at given path: /usr/bin/perl
Then, in konsole command can be written as: perl script.pl

Useful syntax structure in PERL

Comments
In PERL comments can be added using ‘#’ symbol at the beginning of the comment. If, comment
is more than one line than, for every line ‘#’ should be used in the beginning. This is for a single
line comment.

For multiple line comment, = and =cut is used.


= beginning of the multiline comment
This is the second line of comment.
This is the third line of comment.
=cut

Page | 7
Switches

Some of the switches are –e, -n, -c and Pipe


-e
It is used to execute PERL commands from command line instead of from a script. This is not used
in general for scripting, but it is used when someone wants to test simple statements before
using them in to PERL script.
One example is already shown for use of –e.
-n
It is used to print the content of a file. This is important when it comes to printing report after
executing programs. –n also can be used in searching from a file for a particular word match.
$ perl -ne 'print; ' text.txt

-c
It is used to look for syntax error. This is mainly used in web developing CGI (Common Gateway
Interface) scripts where, user input must be checked before submitting a file. This is why
sometimes if a given text box if only numerical value is allowed and if user type any alphabetic
value then this will show error.

Reading from a Pipe

Pipe is represented as |. Since, PERL is used with many other file formats for manipulation of to
give output or to take input from other format of the file
$ date | perl -ne 'print "Today's day, month, time is $_ ";'

This will give an output like given below:


Today is Thursday November 13 16:33:50 PDT 2014
This code will pipe date’s value to the default variable $_. Than it will return value to the
command prompt.

Page | 8
Difference between single quote ’ and double quote ”

Single quote and double quote both are mostly used in printing data. For string both work the
same way, but for, variables and special characters as they work differently. Double quote
interprets variables and special characters while the single quote does not. Single quote considers
variables and special characters as a normal string and print it as it is. Here is an example:
@names = (John, Rebecca, Manuel, Sachin);
print "@list\n"; # this will print all values in an array by interpreting
names array and then new# line will be added.
print '@list\n'; # this will print text @list\n without interpreting
special character and array.
print "\n";

Result:
John Rebecca Manuel Sachin
@list\n

Variables in PERL

There are three kinds of variables. Those are Scalars, Arrays and Hashes. In PERL, variables do not
have any types. While storing in a variable, everything is stored as a string. As it is processed, as
the need requires, it can be treated as numbers or string according to use. If the variable is being
used in an arithmetic expression, it can be treated as number or otherwise it is treated as a string.
So the context in which variable is being used decides type of variable. This is why sometimes it
is called loosely typed language.
Scalars:

Scalar variables hold a single value either string or number and it is preceded by a $ dollar sign.
So, it can be declared as
$variable_name = value.
A variable name can start from any letter other than underscore sign (_). The value of the
variable can be given in any form. If the variable’s value is numerical than no need to include any
quotes, but, if the value of the variable is given in the form of the string then it should be defined
in double quotes.

Page | 9
Declaration of scalars
$one = 1; # this will assign value 1 to the variable one.
$name = "John" # this will assign string John to the variable name.

Some of the system functions can be used in this manner. Like if one wants to define date to the
variable than, linux date function can be used.
$time = 'date';

Expression with Scalars


In PERL expressions can be written down as scalar variables. Syntax is similar to C. Auto increment
and auto decrement is the same as in C language.
$var1 = 100;

Use of auto increment


$var1++; # use of auto increment like in C language
Use of auto decrement
$var1--; # use of auto decrement like in C language.
$var2 = $var1 ** 5; #Two stars indicate exponential operation. This will result in 1005
$var2 = $var2 + $var1;
$var+= $var1; #This is the same as previous line. This shows PERL is pretty similar to C
language

String Concatenation
In PERL, string concatenation can be done using dot(.) operator. For example,
$var1= "Good";
$var2= " Luck";
$var3= $var1.$var2;
print $var3;
Result:
Good Luck
String can also be used in arithmetic operations. In this type of operations, PERL interpreter will
try to find any numbers in the beginning of the string and it will also count dot(.) in a number to
represent floating point number. If, there is no number in the beginning of the string then that
variable’s arithmetic value is taken as 0. This can be shown with following example:
$var1= "1Good";
$var2= $var1+ 1;
$var3= "Good";
$var4= $var3 +1;

Page | 10
print "Case1: 1 in the beginning of the var1 will be added to 1 and total
will be $var2\n"; # use of \n: after printing a statement, pointer will be
moved to next line for next statement printing
print "Case2: no numerical in the beginning of the var1 will result in 0
value. So 0 will be added to 1 and total will be $var4\n";

Result:
Case1: 1 in the beginning of the var1 will be added to 1 and total will be 2
Case2: no numerical in the beginning of the var1 will result in 0 value. So 0 will be added to 1 and
total will be 1

Arrays

While storing similar or different type of data then it is easier to create an array other than
assigning every data to different variables. It can be declared with @ symbol in the beginning of
the array name. Every element in an array can be accessed by the array name followed by square
brackets [number of an element in a list]. So if in the following example Sachin is needed to be
accessed then it can be done in the way shown below. One array can be used in another array.
Here names array is used in class array so, elements of names array will fit-in between lists of
class elements. In, arrays if user do not want to put quotes and comma after each element, for
each entry, then also there is another function qw. This can be used as following
Declaration of an Array
Element declaration in an Array
For printing number of elements in an array, there are two ways. The first is to use scalar keyword
followed by array name to the variable and another way is to assign an array directly to the scalar
variable. Both are shown below in order. Here array list is taken from above example.
@list = (Sachin, John, Rebecca, Manuel, Sachin, Shalin, Maulik);
Counting Array Elements
$total= scalar @list;
$total1= @list;
print "\$total= $total and \$total1= $total1 both are the same\n";

$total= 6 and $total1= 6 both are the same


print " index of the last element is $#list\n" # this will print index of
the last element in an array. It will be (total elements-1). Because, array
indexing starts with 0. Empty array will print -1.
Index of the last element is 5
Removing and adding an element in the beginning of an array can be done by operating an array
using ‘shift’ and ‘unshift’ respectively. Similarly, removing and adding an element at the end or
tail of an array can be done using ‘pop’ and ‘push’ keywords. This is clearly explained in the

Page | 11
following example. With this example another noticeable syntax structure for printing an array is
also shown. This discussion was for only two-dimensional arrays but, just for an information, user
can also define multi-dimensional array in PERL, which is known as matrix or table.
PERL provides a very easy mechanism for shorting list of elements stored in an array. For, shorting
in alphabetic order there is a ‘sort’ keyword. It is shown in the following example. But, for
numerical ordering this does not work correctly. For numerical ordering, ‘sort {$a <=> $b}’
followed by the array name is used.

@list5 = qw/Lloid Mark Betty/;


@list6 = (Sachin,@list5, Shalin,Maulik);
print "old array: @list6\n”

shift

$first= shift @list6; # this will remove element from the beginning of an array
print "New array after applying shift: @list6\n";
@list7 = ('Sachin',@list5, 'Shalin', 'Maulik');

unshift

unshift (@list7,"David"); # this will not replace first element of an array but this will add a new
element at the beginning of an array
print "New array after applying unshift: @list7\n";
print @list7."\n"; # this will type number of elements in an array

use of single and double quotes variation in print statement

print @list,"\n"; # this will type nothing


print "@list7\n"; # this will print an actual array, with space between every
element # add new line at the end of the list
print "@list7"."\n"; # this will print an actual array, with space between
every element add new line at the end of the list

print @list7; #will print an array as it is without any space between


elements pointer will not be shifted to the next line
print @list7, "\n"; #will print an array as it is without any space between
elements pointer will be shifted to the next line for next operation to be
printedprint "\n\n\n# push and pop operation on an array\n";
print "Given array is: @list7 \n";

Page | 12
pop
$last_element = pop(@list7); # last element will be popped out.
print "New array after applying pop: @list7\n";

Push
push (@list7, "George");
print "New array after applying push: @list7\n"; # Last element will be added in an array
print "This is the missing element from array: $last_element \n";

Alphabetic sort
@sorted_a1= sort @list7
print "This is an original array: @list7\n";
print " This is sorted array: @sorted_a1\n";

Numerical sort
print "\n\n\n# numerically shorted array\n";
@marks = (100, 25, 36, 78, 98, 86, 54, 44, 22, 12);
@wrong_sorting = sort @marks;
print "original array containing numerical elements: @marks\n";
print "wrong shorted numerical array: @wrong_sorting\n";
@correct_shorting = sort {$a <=> $b} @marks;
print "Correctly shorted numerical array: @correct_shorting\n";

Result:
old array: Sachin Lloid Mark Betty Shalin Maulik
New array after applying shift: Lloid Mark Betty Shalin Maulik
New array after applying unshift: David Sachin Lloid Mark Betty Shalin Maulik
7
LloidMarkBetty
David Sachin Lloid Mark Betty Shalin Maulik
David Sachin Lloid Mark Betty Shalin Maulik
DavidSachinLloidMarkBettyShalinMaulikDavidSachinLloidMarkBettyShalinMaulik

# push and pop operation on an array


Given array is: David Sachin Lloid Mark Betty Shalin Maulik
New array after applying pop: David Sachin Lloid Mark Betty Shalin

Page | 13
New array after applying push: David Sachin Lloid Mark Betty Shalin George
This is the missing element from array: Maulik

# shorting an array
original array: David Sachin Lloid Mark Betty Shalin George
shorted array: Betty David George Lloid Mark Sachin Shalin

# numerically shorted array


original array containing numerical elements: 100 25 36 78 98 86 54 44 22 12
wrong shorted numerical array: 100 12 22 25 36 44 54 78 86 98
Correctly shorted numerical array: 12 22 25 36 44 54 78 86 98 100

Hashes

Associative array is commonly called as Hash. Hash is a special type of array that contain keys and
with them value assigned. First, one in a pair is called the ‘key’ of that pair and second one is
called the ‘value’ of that pair. Basic difference between array and hash is that array contain
elements in a specific order. While, in hash order of an element does not matter at all because
of the flexibility of accessing value by its key. Among all the elements in this array hash key must
be unique.
Each entry contain a pair of Key and Value. Hash is declared using % symbol. This differentiate
hash from a simple array that is declared using @ symbol. Another method is to type all the keys
and associated values in sequence and it will be automatically assigned every second values to
their associated first key. There are two methods to declare hashes, those are shown below:
Declaration of hashes

1) %class_data = (1=> 'Rohan' ,


2=> 'Shyam' ,
3=> 'John');
In this method, it is implied that whatever appears on the left hand side of the pair is
already in double quoted string. So while declaring by this method, double quote is
optional. Right hand side of => is the value associated with key on left.
2) %class_data = (1, 'Rohan' , 2, 'Shyam' , 3, 'John');
But problem with second type of assignment is that, if data is too long then it gets confusing.

Page | 14
Hashes can be nested. It has 2 functions, those are keys and values.

Conversion from normal array to hash array and from hash array to normal array

While generating hash from an array, pair of values are extracted out and first value of the pair
becomes the ‘key’ and second entry of the pair is called as ‘value’ of the pair. Simple syntax is
shown below.
%class_data = (1=> "Rohan" ,
2=> "Shyam" ,
3=> "John");
foreach $key_of_hashes (keys (%class_data)) {
print "$key_of_hashes\n";
}
foreach $value_of_hashes (values (%class_data)) {
print "$values_of_hashes\n";
}
%class_data1 = ("1", "Rohan" , "2", "Shyam" , "3", "John");

Accessing value
print "name of the person is: $class_data {'1'} with roll number is 1\n";
print "name of the person is: $class_data1 {'2'} with roll number is 2\n";
@array1 = %class_data1;
print "@array1\n";
%reform_hash = @array1;
print "$reform_hash {'1'} is the name of the person with roll number is 1\n";

Results:
123
Rohan Shyam John
name of the person is: Rohan with roll number is 1
name of the person is: Shyam with roll number is 2
2 Shyam 3 John 1 Rohan
Rohan is the name of the person with roll number is 1

Page | 15
Subroutine

In design, many times user need to do some process again and again but, it is very hectic and if
code is long plus, writing the same functionality many times makes code hard to read. It is used
as a user defined function. Main function of subroutine is that it makes program shorter and
easily manageable. Subroutine start with keyword sub followed by the name of the subroutine
and then statements of subroutine.
To call a subroutine, generally & is used. A subroutine can also have parameters, that can be
given as &subroutine_name ($para_1, $para2); # two parameters passed to the subroutine.
Here noticeable thing is that this & sign is optional. In PERL, subroutine can be called without
entering & sign. Subroutine can return some value. In PERL, return statement is also optional.
However, if return statement is omitted, then PERL returns last evaluated value. Return value
can also be non-scalar, which generally other languages do not support.
In subroutine sometimes user want to define some variable for a particular block, then it can be
done by local variables, which are valid until that particular block of code. Local variable in PERL
can be defined using ‘my’ keyword. ‘my’ variable’s storage is freed whenever variable goes
outside the globe.
When data of argument is passed to the subroutine, PERL has default method “Call by Reference”
to save this data. @_ is an array used refer the given arguments.

Call by reference

$total=3;
$total_from_sub = addition (21, 22, -5);
print 'value of $total defined as outside subroutine is '."$total\n";
print 'value of $total defined as inside subroutine is '."$total_from_sub\n";
sub addition {
my $total=0;
foreach $data (@_) {
$total =+ $total;
print 'value of $total defined as local inside subroutine is
'."$total\n";
return $total;
}
}

Result:
value of $total defined as outside subroutine is 3

Page | 16
value of $total defined as inside subroutine is 43

When a copy of the value of the argument is passed to the subroutine variables, it is called “Call
by value” method. So if the copy has been modified by any argument, then original value is not
changed. To provide this functionality, PERL provide function like ‘local’
Call by value
print "\n\n\call by value\n\n";
$one = Vicky;
$two = Dhudashia;
name ($one, $two);
sub name {
local ($first, $last)= @_;
print "Welcome $first , $last \n\n";
}

Result:
call by value

Welcome Vicky , Dhudashia

File Handling

In context of developing server side scripts, CGI scripts, file handling is very important. Before,
going in this detail it is important to know how PERL program interact with user by reading some
input value from keyboard. It is known that many operating system treat a keyboard as a special
file. It is considered a standard input. Similarly, printing data on screen is similar to writing data
into a special file called standard output (STDIN). While program is trying to read from the
keyboard, it assumes that it is reading from the standard input using file handle STDIN. In PERL,
file handle is denoted by angular brackets <>. In general, when user enter any value then for
continue, user enters an ‘enter’ key. But at this time to whichever variable value of STDIN is
assigned, also takes a new line added by enter key. This can jeopardize whole data base. To
remove new line created by the last character input from the keyboard, ‘chomp’ can be used.
chomp function chops off the last entry entered by the user only if it is a new line.

STDIN --- Standard Input

Without using chomp


print "\n\n\n# File handling without using chomp function\n";
print "Enter your name\n";

Page | 17
$name_wc = <STDIN>;
print "Create password for your account\n";
$password_wc = <STDIN>;
print " Welcome to VLSI $name_wc, your password is $password_wc\n";

using chomp
print "\n# File handling using chomp function\n";
print "Enter your name\n";
chomp($name= <STDIN>);
print "Create password for your account\n";
chomp($password= <STDIN>);
print " Welcome to VLSI $name, your password is $password\n";

Result
# File handling without using chomp function
Enter your name
Vicky
Create password for your account
123
Welcome to VLSI Vicky
, your password is 123

# File handling using chomp function


Enter your name
Vicky
Create password for your account
123
Welcome to VLSI Vicky, your password is 123

File Operation in PERL

For opening a file, ‘open’ command can be used. This command returns the file handle value. For
the standard input entered by the user from a keyboard, predefined file handle is <STDIN>.
There is the main difference between STDIN and <STDIN>. STDIN represents a file or handle,
which is standard input. While, <STDIN> represents content of the file. In actual, <> are the line
input character. Some special variables used in printing are $. , $_ and $!.

Default variables in PERL

$. Returns the line number and it starts from 1, not from 0.

Page | 18
$_ Returns the contents of last matched condition.
$! Returns the error message (due to which, operation termination has occurred.)

A file can be opened in 3 modes. The first one is read mode. The second is Write mode and the
third one is append mode.
Read mode is accessible by writing simple script while, variation in write mode is that, file name
in which output is to be written is denoted by ‘>’(greater than sign) followed by the variable
storing file path. This > sign means that program is trying to open that file for output. For
appending an existing file, ‘>>’ is used instead of single greater than sign.

Open

print "\n\n\n# opening and closing file\n";


$file= "/home/perl/openclose/open.txt";
open FILE, $file or die" Error in Opening file: $!";
while (<FILE>) {
print "$:"."$_";
}

close

close FILE;
$file1= "/home/perl/openclose/open1.txt";

Write

# open FILE1, ">open1.txt" or die "Error in Open: $!"; # this also works
open FILE1, ">$file1" or die "Error in Open: $!"; #single quote will not work
here while giving file name or file path
for $p (a..d) {
print FILE1 "$p: Hello, the time is ", scalar(localtime), "\n"; # here print
FILE1 means printing in a file contained by file handle FILE1 instead of
printing in konsole.
}
close FILE1;

Append

open APPEND, ">>$file1" or die " Error in Open: $!\n"; #appending a file
for ($count=1; $count<4; $count++)
{
print APPEND "$count: Hello, the time is ", scalar(localtime), "\n";
print "$count\n";

Page | 19
}
close APPEND;
Result:

# opening and closing file


1: hi how are you?
2: I am file.
3: This file is for simple operation of opening and closing file after editing it using PERL script.
4: good luck for the success.
5: see you soon.
Here is the file open1.txt:
a: Hello, the time is Sat Dec 6 05:38:11 2014
b: Hello, the time is Sat Dec 6 05:38:11 2014
c: Hello, the time is Sat Dec 6 05:38:11 2014
d: Hello, the time is Sat Dec 6 05:38:11 2014
1: Hello, the time is Sat Dec 6 05:38:11 2014
2: Hello, the time is Sat Dec 6 05:38:11 2014
3: Hello, the time is Sat Dec 6 05:38:11 2014
4: Hello, the time is Sat Dec 6 05:38:11 2014

Command line arguments

While compiling or simulating HDL file with given script, user need to provide additional files from
which it needs to take some input or files where output result needed to store or compiler flags.
For this purpose PERL uses special array called @ARGV. List of arguments passed along with PERL
script on the command line. There is a distinct difference between @ARGV and <ARGV>. @ARGV
contains simply list of elements, which are supplied. While in <ARGV> it is assumed that whatever
given after script name, are name of the files from which it will start reading. If, nothing is
specified after script name and still using <ARGV> then it will start reading from the standard
input by default.
ARGV, <ARGV> and <AEGV>

Some standard file handles are <STDIN> which is explained above and <STDOUT> - for printing to
standard output which is generally screen, <STDERR> - for outputting error message.
($#ARGV >= 1) or die "Please give files from which input is to be taken\n";

Page | 20
foreach (<ARGV>) {
print "$_\n";
}

Command from command Line:


perl openperl.pl open.txt

Result:
hi how are you?

I am file.

This file is for simple operation of opening and closing file after editing it using PERL script.

good luck for the success.

see you soon.

In PERL, there are three things, which are considered as false:


Value 0, the empty string (“”) , undef. Everything else in PERL is considered as true.

Control Structures in PERL

Control structures in PERL are mostly the same as a control structures in C programming
language. Available control structures are
• For
• Foreach
• If/else if/else
• While
• Do etc.

Statement block: It is identical as in C. It is a sequence of statements enclosed in matching pair


of {and}. Like C, blocks can be nested within other blocks.

If... else
If (test expression) {
#if true, execute

Page | 21
}
else {
#if false, do this
}

If ($flag ==1) {
Print "There is an error"
}

This explains two things. One is that this can be used without else statement and another thing
noticeable is that here comparison is done with numerical value. So the variable with which it is
comparing can be numerical type. But what if it is string type? In language like C, for comparing
string values, special function are used while, in PERL for comparing string values another
comparison variables are used.

For comparing string type, another type of comparison variables like eq, ne, gt, lt, ge, le.
Comparison Type Numeric String
Equal == eq
Not Equal != ne
Greater Than > gt
Less Than < lt
Greater or Equal >= ge
Less or Equal <= le

There are some logical connectives also, so to connect two or more conditions like execute if
two condition satisfy at a time, or one of two condition satisfied then execute something. There
are mainly three conjunction – and, or, not. Those can be represented like &&, ||, !
The same way extension of if statement, that is if….else if can be used.

While

In C, while can be used to compute numerical values, but PERL is mainly made for string
manipulation. It can be used to make login in script execution. It will be clearer after referring
following example.

$enter_class ='';
$class = 'perl';
print " Please enter the class you are in: ";
while ($class ne $enter_class){
print "\n\nYou might have enter it wrong\n";
print "\n\nTo suspend this operation enter ctrl+z\n OR enter the
class you are in";
chomp ($enter_class = <STDIN>);

Page | 22
}
print "\n\n\n Now you can enter in perl folder\n";
You might have enter it wrong
Please enter the class you are in: perl

Now you can enter in perl folder

For

Syntax is similar to C but, in PERL it can be used in different context.


for ($variable= initial value; termination value; increment/decrement) {
Statements . . . . ;
}

Foreach

This is a construct which iterates over a list.


@fruits = qw/orange apple banana/ {
print $one (@fruits) {
print "Fruit is $one\n";
}

Although ‘for’ and ‘foreach’ are explained different but user can use them interchangeably. In
general for is used to compute numerical value by incrementing or decrementing by going
through a loop.

@array_of_numbers = qw/1 2 3 4 5 6 7 8 9/;


$count =0;
foreach $even_number (@array_of_numbers){
if (($even_number % 2) == 0);
print "The number is Even : $even_number\n";
$count++;
}
print "Total even numbers in given list : $count\n";
}

Breaking out of loop


For breaking the loop last statement is used. It is generally used with condition. So if the condition
is true then it will exit from the loop.

last if (j >4);

Page | 23
Skipping to end of loop

Sometimes while comparing something or computing it becomes necessity to skip the rest of the
statements within an iteration but, not exit from the loop. It will not exit from the loop but, it will
start the next iteration. This statement also used with condition for skipping the rest of the
statements.

next (condition for skipping rest of the statements);

Split function

This function is used to split a string into multiple places using a delimiter, and create a list out of
it.

$colors = "white: red: blue: green: orange";


@colors_splited = split /:/, $colors; #split when : found in string.
foreach (@colors_splited) { #note here: no variable for use in loop
because, remarked
print "$_\n";
}

It will be printed colors one by one.

Regular Expression

It is a very powerful method to specify a character string. It refers to a string pattern, which
follows some rules that are guided by the PERL language. Some time it is needed to search if
particular element is a part of a string or not and this condition can be arbitrary complex. It would
be very helpful in understanding if one can see difference between without RegEx and with
RegEx.

Without RegEx:

$flag = 0;
$_ ="Programming in PERL is very easy";
$search= "easy";

Page | 24
Split function

foreach $content (split) {


if ($content eq $search) {
$flag =1;
last;
}
}
if ($flag) {
print "found the word: $search \n";
}

Without using RegEx


found the word: easy

Using RegEx

print "\n\n\n Using RegEx\n";


$_ ="Programming in PERL is very easy";
if ($_ =~ /easy/) {
print "found the word: $search \n";
}

Using RegEx
found the word: easy

So this it show simpleness of using PERL regular expression. Here ‘=~ ’ operator is used for
searching from the given string and between // the word is specified what to search. The same
way if want to search if a particular word do not exist in a string is specified as! ~ . Here in // white
space also matters.
Types of RegEx:

Matching

In this case user can check if string contains a specified substring or not
It is specified by the ‘m’ symbol. It is optional if forward slash / is used as a delimiter.
Substitution

This is used to replace a substring by another substring. For, this operation‘s’ can be used.
Example for this is given below.

Page | 25
Character Class

There is a character class in PERL that gives flexibility to the user to find any of the substring from
the given string. It is specified using square brackets.
Here ‘my’ keyword is used. This is like defining a local variable.
If, user want to find negation of the substring then at the starting of the character class ^ symbol
can be used. This will try to find out first match at which condition satisfies.

There are some pattern abbreviations which can be used in RegEx, which are listed below:
. anything except newline (\n)
\d a digit same as [0-9]
\w A word character[0-9a-zA-z]
\s A space character (tab, space, etc.)
\D Not a digit, same as [^0-9]
\W Not a word character
\S not a space character

$string ="Good and bad days";


if ($string =~ /d...s/) {# this will find a four letter word with d in the
beginning and s in the ending
print "Found something like days\n";
}
if ($string =~ /\w\w\w\w\s/){ # this will find a four letter word with having
a space after a word
print "Found a four letter word\n";
}

Sometimes while specifying a search condition like search from the beginning of the string or
search from the end of the string, Anchors can be used to specify this conditions,

^ - anchors at the beginning of the string


$ - anchors to the end of the string
\b – anchors to a word boundary

if ($string =~ /^\w/)
This condition searches for the string starting from a word character
if ($string=~ /\d$/)
This condition will check for a string end with a digit
if($string =~ /\bGood\b/)
This condition will search for the word Good

Page | 26
There are some Multipliers for RegEx can be used to check repeated values. Like string starting
with character, any number of alpha numeric can be between and numeric at the end.
‘*’ means: find zero or more occurrences
‘+’ means: find one or more occurrences
‘?’ means: find zero or one occurrence
Example:

$string =~ /^\w+/; # string must begin with a word and there must at least
one more character after that
$string =~ /\d? /; # starts with a digit and followed by another character or
a single digit
$string=~ /\b\w+\s+/; # word boundary followed by a character and then as
many number of characters after that and followed by space

So this way user can combine complex conditions to search from the given string.

Substitution

There are some cases where user not only need to match something from the given file but want
to replace something found in search by another set of string.
Syntax: $variable =~ s/pattern to match/new pattern to replace/;
One noticeable thing about this is it will look for the pattern only once. So if it is found, then only
this first occurrence will be replaced. There is a method to replace all the occurrences of the
pattern matching string. To do this, one have to include /g after the condition.
$string = “John and Don went to the market, which is the main market of the city in which john
live”;
$string =~ s ”/john/Denny/i”; # this statement introduces two concepts.
# /i represents that while matching lowercase or upper case does not make any difference
#this string will be replaced by Denny at the beginning of the string but it will not be replaced at
the end of the string.

Memory in PERL

PERL can memorize the matched cases. User can capture memorized matches from the memory
of the PERL.
If user is still in the same RegEx, last matched cases can be recalled by \1, \2, \3.
But, if user finished RegEx and outside RegEx, last matched cases can be recalled by $1, $2, and
$3.

Page | 27
if ($string =~ / (\w)\1/) {
print "found 2 in a row\n";
}

#for swapping,
$string ="Manan and Chagan are very brilliant";
$string =~ s/ (\w+) and (\w+)/ $2 and $1/ ;

There are some special characters in PERL like $&, $`, $’


$&: represent present match
$`: represent pre match
$’: represents post match
Example:

$_ = 'abcdefghi';
/def/;
print "$\`: $&: $\'\n";

abc: def: ghi

Useful functions for User interaction

Many functions that are useful in making program are explained in this paper like keys, values,
push, pop, delete, chop, and chomp but, there are many functions that makes user interaction
easy.

Read

To interact with user, for example to receive a specific word from the user this function can be
used. It allows user to read number of bytes into a variable from a specified filehandle. Example:

$number_of_bits = read (STDIN, $data, 10); # 10 is the limit of character,


that read function takes from provided file or file handle
print "You entered: $data";
print "The number of characters read was: $number_of_bits.\n";

jelly been
You entered: jelly been
The number of characters read was: 10

Page | 28
die
Use of this function is to terminate program.
do
Used to include subroutine from PERL subroutine library.
exit
For exiting any loop or sequence of statements. But, it is not recommended to use this function
in subroutine.

$one = <STDIN>;
exit 0 if $one=~ /number/;

grep
This function evaluates block of data to match the expression and save each lines with matches
expression in an array. Later, those lines, containing expression can be printed by assigning this
function’s output to an array and then printing this array.
@array = grep {/flip+/i , @string_file};

Page | 29
Verilog Design

In this paper, simple example of ripple carry adder is taken that design is done on gate level and
compilation and simulation is done in VCS compiler.

The following file is saved as rca8.v

`timescale 1 ns / 10 ps
module rca8(sum,c_out,oper1,oper2,c_in,clock,reset);
output [7:0] sum;
output c_out;
input [7:0] oper1, oper2;
input c_in, clock, reset;
wire [7:0] sumbl;
wire c_outbl,c4;
reg [7:0] oper1lt, oper2lt, sum;
reg c_inlt, c_out;

rca4 u0(sumbl[3:0],c4,oper1lt[3:0],oper2lt[3:0],c_inlt);
rca4 u1(sumbl[7:4],c_outbl,oper1lt[7:4],oper2lt[7:4],c4);
always @(posedge clock or posedge reset) begin
if (reset) begin
oper2lt<=8'd0;
oper1lt<=8'd0;
sum<=8'd0;
c_inlt<=1'b0;
c_out<=1'b0;
end else begin
oper2lt<=oper2;
oper1lt<=oper1;
c_inlt<=c_in;
sum<=sumbl;
c_out<=c_outbl;
end
end
endmodule

//rca4

Page | 30
`timescale 1ns/10ps
module rca4(sum,c_out,oper1,oper2,c_in);

input[3:0] oper1,oper2;
input c_in;
output[3:0] sum;
output c_out;

xor(p0,oper1[0],oper2[0]) ;
and(g0,oper1[0],oper2[0]);
and(k0,p0,c_in);
or(c1,g0,k0);
xor(sum[0],p0,c_in);

xor(p1,oper1[1],oper2[1]) ;
and(g1,oper1[1],oper2[1]);
and(k1,p1,c1);
or(c2,g1,k1);
xor(sum[1],p1,c1);

xor(p2,oper1[2],oper2[2]) ;
and(g2,oper1[2],oper2[2]);
and(k2,p2,c2);
or(c3,g2,k2);
xor(sum[2],p2,c2);

xor(p3,oper1[3],oper2[3]) ;
and(g3,oper1[3],oper2[3]);
and(k3,p3,c3);
or(c4,g3,k3);
xor(sum[3],p3,c3);

assign c_out=c4;

endmodule

Page | 31
Verilog Test Bench
The following file is saved as rca8test.v

`timescale 1ns/10ps
module rca8test();

reg[7:0]oper1,oper2;
reg c_in,clock,reset;
wire[7:0]sum;
wire c_out;

initial begin
$dumpvars(0,rca8test);
$dumpfile("rca8.vcd");
end

rca8
t0(.sum(sum),.c_out(c_out),.oper1(oper1),.oper2(oper2),.c_in(c_in),.clock(clock),.reset(reset));

initial begin
$display (" \n RTL simulation report \n" );
$monitor($time,"\toper1=%d,oper2=%d,c_in=%d,reset=%d,c_out=%d,sum=%d
\n",oper1,oper2,c_in,reset,c_out,sum);

end

////////

///////
/*
initial begin
//$display ("\toper1 \toper2 \tc_in \treset \tsum \tc_out\t"); // dont use anytime

//$monitor ("\t%d \t%d \t%d \t%d \t%d \t%d" , oper1,oper2,c_in,reset,sum,c_out); ///


dont use it

Page | 32
$display ($realtime,"\toper1lt %d \toper2lt %d\tc_inlt %d\treset %d\tsumbl
%d\tc_outbl t%d",t0.oper1lt,t0.oper2lt,t0.c_inlt,t0.reset,t0.sumbl,t0.c_outbl);
//// use it for presynthesis sim and postsynthesis

$monitor($realtime,"\toper1lt %d \toper2lt %d\tc_inlt %d\treset %d\tsumbl


%d\tc_outbl t%d",t0.oper1lt,t0.oper2lt,t0.c_inlt,t0.reset,t0.sumbl,t0.c_outbl);
/// use it for presythesis sim and post synthesis
end
*/
/////////

initial begin
reset=1'b1;
#20 oper1= 8'd0; oper2=8'd0; c_in= 1'b0; reset= 1'b0;
#20 oper1= 8'd0; oper2=8'd1; c_in= 1'b0;
#20 oper1= 8'd255; oper2=8'd254; c_in= 1'b1;
#20 oper1= 8'd240; oper2=8'd15; c_in= 1'b0;
#20 oper1= 8'd255; oper2=8'd0; c_in= 1'b1;
#20 oper1= 8'd188; oper2=8'd68; c_in= 1'b0;
#20 oper1= 8'd0; oper2=8'd0; c_in= 1'b0;
#20 oper1= 8'd240; oper2=8'd15; c_in= 1'b0;
#20 oper1= 8'd240; oper2=8'd143; c_in= 1'b1;
#20 oper1= 8'd0; oper2=8'd0; c_in= 1'b0;
#20 oper1= 8'd94; oper2=8'd172; c_in= 1'b1;
#20 oper1= 8'd0; oper2=8'd0; c_in= 1'b0;
#20 oper1= 8'd170; oper2=8'd85; c_in= 1'b0;
#20 oper1= 8'd255; oper2=8'd255; c_in= 1'b1;
#20 oper1= 8'd170; oper2=8'd85; c_in= 1'b1;
#20 oper1= 8'd3; oper2=8'd5; c_in= 1'b1;
#20 oper1= 8'd100; oper2=8'd158; c_in= 1'b0;
#20 oper1= 8'd200; oper2=8'd11; c_in= 1'b1;
#20 oper1= 8'd240; oper2=8'd15; c_in= 1'b1;
#20 oper1= 8'd125; oper2=8'd125; c_in= 1'b1;
#20 $finish;
end
initial clock= 1'b0;
always begin
#5 clock=~clock;
end
endmodule

Page | 33
PERL Script

#! usr/bin/perl

$password_entered ='';
$password_RCA8 = 'orange';
print " Please enter the password to run this script: ";
while ($password_RCA8 ne $password_entered){ #this will check for password
print "\n\nInvalid Password. Try again\n\n";
print "\n\nTo suspend this operation enter ctrl+z\n Enter the
passwoed: ";
chomp ($password_entered = <STDIN>);
}
print "\n\n\n Password is correct: \n\n\n";
print "Now your script will run
\n\nGood Luck\n\n";
#use strict; # useful to indicate use of undefined variable
#use warnings;
use Getopt::Long;
$debug = " ";
$synthesis = " ";
$clk = $ARGV[2]; # third argument provided is clock period
sub SYNTHESIS_SCRIPT{ # subroutine for synthesis
open SYNTHESIS, ">synthesis.script" or die"\nError in opening synthesis
script\n"; #open file for writing
printf SYNTHESIS "
set link_library {/apps/toshiba/sjsu/synopsys/tc240c/tc240c.db_WCCOM25
dw_foundation.sldb}
set target_library {/apps/toshiba/sjsu/synopsys/tc240c/tc240c.db_WCCOM25
/apps/toshiba/sjsu/synopsys/tc240c/tc240c.db_BCCOM25}
set symbol_library {/apps/toshiba/sjsu/synopsys/tc240c/tc240c.workview.sdb}

read_verilog RCA8.v;
current_design rca8
link
check_design -multiple_designs;

set_min_library /apps/toshiba/sjsu/synopsys/tc240c/tc240c.db_WCCOM25 -
min_version /apps/toshiba/sjsu/synopsys/tc240c/tc240c.db_BCCOM25

create_clock clock -name clock -period $clk;


set_propagated_clock clock
set_clock_uncertainty 0.25 clock
set_propagated_clock clock
set_fix_hold clock

set_max_delay 2.35 -from [all_inputs]


set_max_delay 2.35 -to [all_outputs]

Page | 34
#set_min_delay 5.0 -from [all_inputs]
#set_min_delay 5.0 -to [all_outputs]

set_max_area 1000

compile -map_effort medium


update_timing
report_qor
report -cell
report_timing -max_paths 10

report_area
report_power
write -hierarchy -format verilog -output rca8_design.v
quit
";
close (SYNTHESIS);
}

SYNTHESIS_SCRIPT; # call subroutine

($#ARGV >=2) or die "provide verilog file, test bench file, clock period for
synthesis";

system ("vcs +v2k $ARGV[0] $ARGV[1]")==0 or die "problem in executing VCS";


# run vcs for compilation
print "\n\n\nVCS compilation finished\n\n\n";
print "\n\n\nStarting simulation\n\n\n";
# system function for simulation and presynthesis
system("./simv | tee reportsimv.txt");
system ("dc_shell -xg -f synthesis.script | tee pre_synthesis_report.txt");
print "\n\n\nnow starting to find latch\n\n\n";
# file handling for extracting desired data from file
system ("grep -i error pre_synthesis_report.txt")!= 0 or die "\n\nYour design
contain Errors\n\n";
system ("grep -i violated pre_synthesis_report.txt")!= 0 or die "\n\nTiming
Violation..\n\n";

system ("grep -i latch pre_synthesis_report.txt")!=0; or die "\n\nYour design


contaon Latch. Remove Latch and try again..\n\n";
$out = `grep Total synres.txt`;
print "$out\n\n"; # print data matched
system "vcs +v2k -y /export/apps/toshiba/sjsu/verilog/tc240 +libext+.tsbvlibp
rca8test.v rca8_gates.v")==0 or die "Failed in Synthesis\n\n"; # run
synthesis

print "Completed compilation, simulation and Synthesis";

Page | 35
Conclusion

After reading this paper, one can come to know how easy it is to learn PERL. Even though this
tutorial does not cover all topics in the PERL language, it gives the reader a basic idea on how to
automate the scripting process and save a lot of time for running RTL designs.
With PERL, one can do many things such as string handling, error handling, file I/O operations,
report manipulation and extraction in a very convenient manner. PERL makes execution of files
seem like a piece of cake and it completes various tasks in a much better way than any other
scripting language, which is one of the most impo
Power of PERL is that, one can do so many things like string handling, error handling, file i/o
handling, report manipulation and extraction in very easy way. PERL makes execution of files very
friendly and it helps in doing tasks in easy way, which is hard by any other programming language.
This is very important for designing. So only after one modification user does not have to enter
all command every time.

Page | 36

Вам также может понравиться