0% found this document useful (0 votes)
419 views

Vlsi Design Automation Using Perl

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

Vlsi Design Automation Using Perl

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

VLSI DESIGN AUTOMATION

USING PERL
INTRODUCTION:
• It stands for Practical Extraction and Report Language developed by
Larry Wall, especially designed for text processing.
• Perl is a general-purpose programming language originally developed for
text manipulation and now used for a wide range of tasks including
system administration, web development, network programming, GUI
development, and more.
• It runs on a variety of platforms, such as Windows, Mac OS, and the
various versions of UNIX.

Perl - Syntax Overview


• A Perl program consists of a sequence of declarations and statements,
which run from the top to the bottom.
• Loops, subroutines, and other control structures allow you to jump
around within the code.
• Every simple statement must end with a semicolon (;).
WHY TO LEARN PERL ?
• PERL makes you efficient.
• There are 2 kinds of automation.
a. Automation in day to day life for industrial applications.
.Ex: grading for groundnuts, automatic farm irrigation, etc.
. PERL has no significance here. It is done using ARM boards.
b. Automation of the things done in computer system related job.
. PERL or python can be used to make these efficient.
• Every job across domains has some kind of repetitive work that needs to
be done manually. PERL can automate all these aspects, so that we can
spend time on other important aspects of job.
a. Checking the testcase pass/ fail status.
.make report out of it in different formats like xls, html, word.
b. Creating environment files/ removing some of them.
c. Updating all existing files for some project specific updates.
d. Running testcases including compilation, elaboration, simulation.
e. Running same test case with different configurations.
• Many job openings specifically require hands on exposure on PERL.
WHY TO LEARN PERL ?

• PERL reduces all the above effort.


a. Reduce manual effort, human errors.
b. Scripts are reusable.
c. There is huge resource of PERL modules (pre-implemented libraries) which
makes it easy toa any kind of jobs across different work domains.
(VLSI/Embedded/Software/etc)
d. There are 10000’s of PERL modules – to create xls, parse xlx, parse html,
create html, compare html are few to name.
e. PERL is open source, any one can develop their PERL module and release
as a
part of PERL package.
f. www.cpan.org lists all PERL modules.
• PERL essentially helps to reduce manual effort and give user more time to focus
on important aspects of job.
PERL BASICS:

• Open Source, released as a package of basic set of PERL modules.


• User can install additional modules on need .
• Interpreted High level Programming language.
a. C language handles data types only at character level, whereas PERL can
treat one complete line of code as a single variable.
• Programming Language Basics
a. Compiled Language (Ex: C, C++)
. Compilation and Linking
. Transformation to machine code
• Interpreted Language (Ex: PERL)
a. No Compilation
b. Interpreter is required to execute the source code. /usr/bin/perl
• PERL script is executed line by line without compilation.
a. If the script has errors, produces the output till it reaches any error in the
code, then exists at the line which has error.
b. If the script has no error, script will be executed till last line.
PERL for VLSI:
• Setting up Regression
. Automate the compile and simulation run process for all the tests.
• Automate the process of reporting results
. Analyse the simulation log files
. Report results in different formats
. Text Format, HTML format
• Setting up Design and Test bench environment directory structure.
• Recursive update of files in design and test bench hierarchy.
. Adding header information to all the files in the environment.
.Replace piece of code with a new code
• Analyse long text files
. PERL alayzes text files on line by line basis rather than character basis
as in ‘C’ language.
PERL Practical Usage:

• Recursive directory traversing and file creation/updating


• Ex: we have developed a TB for chip named XYZ, we want port the same TB
to other chip ABC, with some minimal changes.
. Requires manually doing project name changes across directories and files.
. PERL script can completely automate this process.
• Generating complete TB using Spreadsheet input
. We get an XLS with design block name, interface names, types of interface, clock
name and clock frequency. Using this we can generate complete TB.
• Setting up Regression, Analyzing regression outputs, creating report.
• Generating register model (SV & UVM) using spreadsheet input.
• Non VLSI
. Server management
. Spreadsheet data handling
. Resume filtering
Hello world Program:
• A Perl program consists of a sequence of statements, loops, subroutines, etc.
that allows moving around within the code easily.
• Every statement in a Perl code must end with a semicolon(;).

#!/usr/bin/perl Path for PERL interpreter


# This will print "Hello, World" #: Comment, \
print "Hello, world\n"; n: new line

$chmod 0755 hello.pl $./hello.pl

Print is an standard PERL keyword to print


text to screen.
Modes of Writing Code:
• Interactive Mode
•Scripting Mode
•One-Liner Mode
•These modes can be RUN on the command line with the use of perl keyword or
on the online IDE’s in the form of block of code.

INTERACTIVE MODE OF CODING:


• Interactive mode of writing a perl code means direct interaction with the interpreter.
• Interactive mode in PERL can be used on the command line with the help of PERL
Debugger. This interpreter is commonly called as REPL.- Read, Evaluate, Print, Loop.
• perl –de1 will open the debugger mode in perl command.
• In interactive mode, the user has to write the code line by line and it gets executed
at the same time.
• Interactive mode in perl can be RUN on command line itself without use of perl
debugger
• Perl –e Code_statement;
Perl –de1
EXAMPLE: If we need to add two numbers and display the result then
that can be done in the Interactive mode in the following manner

This statement uses the -e flag to avoid the creation of a script. This
method of writing in an Interactive mode will not allow the user to
write a Multiline code as in the debugger.
SCRIPTING MODE:
• Script Mode in Perl is used to write Perl programs which have more than a few
lines of code and are a bit complex for the Interactive mode.
• Script mode in Perl can be used by the help of a text editor to write the Perl
program and to save it in a file called a script and then execute the saved file
by using the command line.
• This file must be saved with a .pl extension and should be placed in the same
folder of which the directory path is given to the command line.

perl File_Name.pl perl Perl_program.pl


ONE-LINER MODE:
• Perl also provides a one-liner mode, which allows to type and execute a
very short script of code directly on the command line.
• This is done to avoid the creation of Files to store the script for codes
which are not very lengthy.
• These codes can be typed on a single line in the command line mode
with the help of the following command:

Perl –e
Example:
• parentheses for functions arguments can be usedor omit them according to your personal
taste.

print("Hello, world\n");
print "Hello, world\n";

Perl File Extension


• A Perl script can be created inside of any normal simple-text editor program.
• a Perl file must be saved with a .pl or .PL file extension in order to be
recognized as a functioning Perl script.
• File names can contain numbers, symbols, and letters but must not contain
a space.
• Use an underscore (_) in places of spaces.
Comments in Perl
• A line starting with hash # is a comment in perl.

• Lines starting with =begin are interpreted as the start of a section of


embedded documentation (pod), and all subsequent lines until the next
=cut are ignored by the compiler.

#!/usr/bin/perl
# This is a single line comment
print "Hello, world\n";
=begin comment
This is all part of multiline comment. You can use as
many lines as you like These comments will be ignored
by the compiler until the next =cut is encountered.
=cut
Whitespaces in Perl
• A Perl program does not care about whitespaces

#!/usr/bin/perl
print "Hello, world\n";
• But if spaces are inside the quoted strings, then they would be printed as is .

#!/usr/bin/perl
# This would print with a line break in the middle
print "Hello
world\n";
Single and Double Quotes in Perl
• Only double quotes interpolate variables and special characters such as
newlines \n, whereas single quote does not interpolate any variable or
special character.

#!/usr/bin/perl
print "Hello, world\n";
print 'Hello, world\n';

#!/usr/bin/perl $a = 10;
print "Value of a = $a\n";
print 'Value of a = $a\n';
EOF:
OUTPUT:
Escaping Characters
• Perl uses the backslash (\) character to escape any type of character
that might interfere with our code.

#!/usr/bin/perl
$result = "This is \"number\"";
print "$result\n";
print "\$result\n";
Perl Identifiers
• A Perl identifier is a name used to identify a variable, function, class,
module, or other object.

• A Perl variable name starts with either $, @ or % followed by zero or


more letters, underscores, and digits (0 to 9).

• Perl does not allow punctuation characters such as @, $, and % within


identifiers.

• Perl is a case sensitive programming language.

Thus $hello and $Hello are two different identifiers in Perl.


Perl - Data Types
• Perl has three basic data types: scalars, arrays of scalars, and hashes of scalars,
also known as associative arrays.

Sr.No. Types & Description

Scalar
Scalars are simple variables. They are preceded by a dollar sign ($). A scalar
1
is either a number, a string, or a reference. A reference is actually an
address of a variable, which we will see in the upcoming chapters.

Arrays
2 Arrays are ordered lists of scalars that you access with a numeric index,
which starts with 0. They are preceded by an "at" sign (@).

Hashes
3 Hashes are unordered sets of key/value pairs that you access using the keys
as subscripts. They are preceded by a percent sign (%).
Numeric Literals
• Perl stores all the numbers internally as either signed integers or double-
precision floating-point values.
• Numeric literals are specified in any of the following floating-point or integer
formats −

Type Value
Integer 1234
Negative integer -100
Floating point 20.00
Scientific notation 16.12E14
Hexadecimal 0xffff
Octal 0577
String Literals
• Strings are sequences of characters.
• They are usually alphanumeric values delimited by either single (') or double
(") quotes.
• Double-quoted string literals allow variable interpolation, and single-quoted
strings are not.
• There are certain characters when they are proceeded by a back slash, have
special meaning and they are used to represent like newline (\n) or tab (\t).

Escape sequence Meaning


\\ Backslash
\' Single quote
\" Double quote
Escape
Meaning
sequence
\a Alert or bell
\b Backspace
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\0nn Creates Octal formatted numbers
Creates Hexideciamal formatted
\xnn
numbers
OUTPUT:
Perl - Variables
• Variables are the reserved memory locations to store values.
• This means that when you create a variable you reserve some space in memory.
• Based on the data type of a variable, the interpreter allocates memory and
decides what can be stored in the reserved memory.
• Therefore, by assigning different data types to variables, you can store integers,
decimals, or strings in these variables.
• Perl has 3 data types : Scalars, Arrays, Hashes.
• A scalar variable will precede by a dollar sign ($) and it can store either a
number, a string, or a reference.
• An array variable will precede by sign @ and it will store ordered lists of scalars.
• The Hash variable will precede by sign % and will be used to store sets of
key/value pairs.
• We can use the same name for a scalar variable, an array, or a hash. This means
that $hello and @hello are two different variables.
Creating Variables
• Perl variables do not have to be explicitly declared to reserve memory space.
• The declaration happens automatically when you assign a value to a variable.
• The equal sign (=) is used to assign values to variables.
• The operand to the left of the = operator is the name of the variable, and the
operand to the right of the = operator is the value stored in the variable .

$age = 25; # An integer assignment


$name = "John Paul"; # A string
$salary = 1445.50; # A floating point
Scalar Variables
• A scalar is a single unit of data.
• That data might be an integer number, floating point, a character, a
string, a paragraph, or an entire web page

#!/usr/bin/perl
$age = 25; # An integer assignment
$name = "John Paul"; # A string
$salary = 1445.50; # A floating point
print "Age = $age\n";
print "Name = $name\n";
print "Salary = $salary\n";
Array Variables
• An array is a variable that stores an ordered list of scalar values.
• Array variables are preceded by an "at" (@) sign.
• To refer to a single element of an array, you will use the dollar sign ($)
with the variable name followed by the index of the element in square
brackets.
Hash Variables
• A hash is a set of key/value pairs. Hash variables are preceded by a percent
(%) sign.
• To refer to a single element of a hash, you will use the hash variable name
followed by the "key" associated with the value in curly brackets.

#!/usr/bin/perl
%data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);

print "\$data{'John Paul'} = $data{'John Paul'}\n";


print "\$data{'Lisa'} = $data{'Lisa'}\n";
print "\$data{'Kumar'} = $data{'Kumar'}\n";
Variable Context
Perl treats same variable differently based on Context, i.e., situation where a
variable is being used.

#!/usr/bin/perl
@names = ('John Paul', 'Lisa', 'Kumar’);
@copy = @names;
$size = @names;
print "Given names are : @copy\n";
print "Number of names are : $size\n";
PERL SCALARS:
• A scalar is a single unit of data. That data might be an integer number,
floating point, a character, a string, a paragraph, or an entire web page.
NUMERIC SCALARS:
• A scalar is most often either a number or a string
STRING SCALARS:
SCALAR OPERATORS
Multiline Strings
SPECIAL LITERALS:
• three special literals __FILE__, __LINE__, and __PACKAGE__ represent
the current filename, line number, and package name at that point
in your program.
PERL-ARRAYS:
• An array is a variable that stores an ordered list of scalar values.
• Array variables are preceded by an "at" (@) sign.
• To refer to a single element of an array, you will use the dollar sign
($) with the variable name followed by the index of the element in
square brackets.

Array Creation
Array variables are prefixed with the @ sign and are populated using
either parentheses or the qw operator.

@array = (1, 2, 'Hello'); @array


= qw/This is an array/
• The second line uses the qw// operator, which returns a list of strings,
separating the delimited string by white space.
• In this example, this leads to a four-element array; the first element is 'this'
and last (fourth) is 'array'.
• You can also populate an array by assigning each value individually as follows −
$array[0] = 'Monday’;
...
$array[6] = 'Sunday';

Accessing Array Elements


• When accessing individual elements from an array, you must prefix the
variable with a dollar sign ($) and then append the element index within the
square brackets after the name of the variable.
#!/usr/bin/perl
@days = qw/Mon Tue Wed Thu Fri Sat Sun/;
print "$days[0]\n";
print "$days[1]\n";
print "$days[2]\n";
print "$days[6]\n"; print "$days[-1]\n";
print "$days[-7]\n";
Sequential Number Arrays
• Perl offers a shortcut for sequential numbers and letters. Rather than
typing out each element when counting to 100

#!/usr/bin/perl
@var_10 = (1..10);
@var_20 = (10..20);
@var_abc = (a..z);
print "@var_10\n"; # Prints number from 1 to 10
print "@var_20\n"; # Prints number from 10 to 20
print "@var_abc\n"; # Prints number from a to z
Array Size
• The size of an array can be determined using the scalar context on the
array - the returned value will be the number of elements in the array.
• The value returned will always be the physical size of the array, not the
number of valid elements.

#!/usr/bin/perl
@array = (1,2,3);
$array[50] = 4;
$size = @array;
$max_index = $#array;
print "Size: $size\n";
print "Max Index: $max_index\n";
Adding and Removing Elements in Array
• Perl provides a number of useful functions to add and remove elements in an
array

S.No Types & Description


push @ARRAY, LIST
1
Pushes the values of the list onto the end of the array.
pop @ARRAY
2
Pops off and returns the last value of the array.
shift @ARRAY
3 Shifts the first value of the array off and returns it, shortening the
array by 1 and moving everything down.
unshift @ARRAY, LIST
4 Prepends list to the front of the array, and returns the number of
elements in the new array.
Slicing Array Elements
• You can also extract a "slice" from an array - that is, you can select more than
one item from an array in order to produce another array.

#!/usr/bin/perl
@days = qw/Mon Tue Wed Thu Fri Sat Sun/;

@weekdays = @days[3,4,5];
print "@weekdays\n";

@weekdays = @days[3..5];
Print “@weekdays\n”;
Replacing Array Elements

splice @ARRAY, OFFSET [ , LENGTH [ , LIST ] ]


• This function will remove the elements of @ARRAY designated by OFFSET
and LENGTH, and replaces them with LIST, if specified.
• Finally, it returns the elements removed from the array.

#!/usr/bin/perl
@nums = (1..20);
print "Before - @nums\n";
splice(@nums, 5, 5, 21..25);
print "After - @nums\n";
Transform Strings to Arrays

split [ PATTERN [ , EXPR [ , LIMIT ] ] ]


• This function splits a string into an array of strings, and returns it.
• If LIMIT is specified, splits into at most that number of fields.
• If PATTERN is omitted, splits on whitespace.

Transform Arrays to Strings


• We can use the join() function to rejoin the array elements and form
one long scalar string.

join EXPR, LIST


• This function joins the separate strings of LIST into a single string with fields
separated by the value of EXPR, and returns the string
Sorting Arrays
• The sort() function sorts each element of an array according to the ASCII
Numeric standards

sort [ SUBROUTINE ] LIST


• This function sorts the LIST and returns the sorted array value.
• If SUBROUTINE is specified then specified logic inside the SUBTROUTINE is
applied while sorting the elements.
Merging Arrays

• Because an array is just a comma-separated sequence of values, you can


combine them together

#!/usr/bin/perl
@numbers = (1,3,(4,5,6));
print "numbers = @numbers\n";

#!/usr/bin/perl
@odd = (1,3,5);
@even = (2, 4, 6);
@numbers = (@odd, @even);
print "numbers = @numbers\n";
Selecting Elements from Lists

• The list notation is identical to that for arrays. You can extract an element from
an array by appending square brackets to the list and giving one or more
indices

#!/usr/bin/perl
@list = (5,4,3,2,1)[1..3];
print "Value of list = @list\n";

$var = (5,4,3,2,1)[4];
print “ Value of var = $var\n”;
Perl - Hashes

• A hash is a set of key/value pairs. Hash variables are preceded by a


percent (%) sign.
• To refer to a single element of a hash, you will use the hash variable name
preceded by a "$" sign and followed by the "key" associated with the value
in curly brackets..

Creating Hashes
• Hashes are created in one of the two following ways.
• In the first method, you assign a value to a named key on a one-by-one
basis −

$data{'John Paul'} = 45;


$data{'Lisa'} = 30;
$data{'Kumar'} = 40;
• In the second case, you use a list, which is converted by taking individual
pairs from the list: the first element of the pair is used as the key, and the
second, as the value.

%data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);


For clarity, you can use => as an alias for , to indicate the key/value pairs as
follows −

%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
• here all the keys have been preceded by hyphen (-) and no quotation is
required around them −

%data = (-JohnPaul => 45, -Lisa => 30, -Kumar => 40);
Accessing Hash Elements

• When accessing individual elements from a hash, you must prefix the variable
with a dollar sign ($) and then append the element key within curly brackets
after the name of the variable.

#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
print "$data{'John Paul'}\n";
print "$data{'Lisa'}\n";
print "$data{'Kumar'}\n";
Extracting Slices

• You can extract slices of a hash just as you can extract slices from an array.
• You will need to use @ prefix for the variable to store the returned value
because they will be a list of values.

#!/uer/bin/perl
%data = (-JohnPaul => 45, -Lisa => 30, -Kumar => 40);
@array = @data{-JohnPaul, -Lisa};
print "Array : @array\n";
Extracting Keys and Values

• You can get a list of all of the keys from a hash by using keys function,
which has the following syntax
keys %HASH
• you can use values function to get a list of all the values. This function
has the following syntax − values %HASH
Checking for Existence

• If you try to access a key/value pair from a hash that doesn't exist, you'll
normally get the undefined value, and if you have warnings switched on, then
you'll get a warning generated at run time.
• You can get around this by using the exists function, which returns true if the
named key exists, irrespective of what its value might be.

#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
if( exists($data{'Lisa'} ) ) {
print "Lisa is $data{'Lisa'} years old\n";
} else {
print "I don't know age of Lisa\n";
}
Getting Hash Size

• You can get the size - that is, the number of elements from a hash by
using the scalar context on either keys or values.
• Simply saying first you have to get an array of either the keys or values
and then you can get the size of array.

#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar'
=> 40);
@keys = keys %data;
$size = @keys;
print "1 - Hash size: is $size\n";
@values = values %data;
$size = @values;
print "2 - Hash size: is $size\n ”;
Add and Remove Elements in Hashes

• Adding a new key/value pair can be done with one line of code using simple
assignment operator.
• But to remove an element from the hash you need to use delete function.
Perl Conditional Statements - IF...ELSE

• Perl conditional statements helps in the decision making, which require that the
programmer specifies one or more conditions to be evaluated or tested by the
program, along with a statement or statements to be executed if the condition
is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.
Sr.No. Statement & Description
if statementAn if statement consists of a boolean expression followed by
1
one or more statements.
if...else statementAn if statement can be followed by an optional else
2
statement.
if...elsif...else statementAn if statement can be followed by an
3
optional elsif statement and then by an optional else statement.
unless statementAn unless statement consists of a boolean expression
4
followed by one or more statements.
unless...else statementAn unless statement can be followed by an
5
optional else statement.
unless...elsif..else statementAn unless statement can be followed by
6
an optional elsif statement and then by an optional else statement.
switch statementWith the latest versions of Perl, you can make use of
7 the switch statement. which allows a simple way of comparing a variable
value against various conditions.
Perl IF Statement
• A Perl if statement consists of a boolean expression followed by one
or more statements.
if(boolean_expression) {
# statement(s) will execute if the given condition is true
}
Perl IF...ELSE statement
• A Perl if statement can be followed by an optional else statement, which
executes when the boolean expression is false.
if(boolean_expression) {
# statement(s) will execute if the given condition is true
} else {
# statement(s) will execute if the given condition is false
}
Perl IF...ELSIF statement
• An if statement can be followed by an optional elsif...else statement,
which is very useful to test the various conditions using single if...elsif
statement.

if(boolean_expression 1) {
# Executes when the boolean expression 1 is true
} elsif( boolean_expression 2) {
# Executes when the boolean expression 2 is true
} elsif( boolean_expression 3) {
# Executes when the boolean expression 3 is
true } else {
# Executes when the none of the above condition
is true
}
Perl unless Statement

unless(boolean_expression) {
# statement(s) will execute if the given condition is false
}
Perl UNLESS...ELSE statement
unless(boolean_expression) {
# statement(s) will execute if the given condition is false
} else {
# statement(s) will execute if the given condition is true
}
Perl UNLESS...ELSIF statement

unless(boolean_expression 1) {
# Executes when the boolean expression 1 is false
} elsif( boolean_expression 2) {
# Executes when the boolean expression 2 is true
} elsif( boolean_expression 3) {
# Executes when the boolean expression 3 is true
} else {
# Executes when the none of the above condition is met
}
Perl switch Statement
• A switch statement allows a variable to be tested for equality against a
list of values. Each value is called a case, and the variable being
switched on is checked for each switch case.
The ? : Operator

Exp1 ? Exp2 : Exp3;


Perl - Loops

• There may be a situation when you need to execute a block of code several
number of times.
• In general, statements are executed sequentially: The first statement in a
function is executed first, followed by the second, and so on.
• A loop statement allows us to execute a statement or group of statements
multiple times
Sr.No. Loop Type & Description

while loopRepeats a statement or group of statements while


1 a given condition is true. It tests the condition before
executing the loop body.
until loopRepeats a statement or group of statements until a
2 given condition becomes true. It tests the condition before
executing the loop body.
for loopExecutes a sequence of statements multiple times
3
and abbreviates the code that manages the loop variable.
foreach loopThe foreach loop iterates over a normal list value
4 and sets the variable VAR to be each element of the list in
turn.
do...while loopLike a while statement, except that it tests the
5
condition at the end of the loop body
nested loopsYou can use one or more loop inside any another
6
while, for or do..while loop.
Perl while Loop
• A while loop statement in Perl programming language repeatedly
executes a target statement as long as a given condition is true.

while(condition) {
statement(s);
}
#!/usr/local/bin/perl
$a = 10;
# while loop execution
while( $a < 20 ) {
printf "Value of a: $a\n"; $a = $a + 1;
}
Perl until Loop
• An until loop statement in Perl programming language repeatedly executes a
target statement as long as a given condition is false.

until(condition) {
statement(s);
}
#!/usr/local/bin/perl
$a = 5;
# until loop execution
until( $a > 10 ) {
printf "Value of a: $a\n"; $a = $a + 1;
}
Perl for Loop
• A for loop is a repetition control structure that allows you to efficiently write a
loop that needs to execute a specific number of times.

for ( init; condition; increment ) {


statement(s);
}
#!/usr/local/bin/perl
# for loop execution
for( $a = 10; $a < 20; $a = $a + 1 ) {
print "value of a: $a\n";
}
Perl foreach Loop
• The foreach loop iterates over a list value and sets the control variable (var)
to be each element of the list in turn.
foreach var (list) {
...
}

#!/usr/local/bin/perl
@list = (2, 20, 30, 40, 50);
# foreach loop execution
foreach $a (@list) {
print "value of a: $a\n";
}
Perl do...while Loop
• Unlike for and while loops, which test the loop condition at the top of the
loop, the do...while loop checks its condition at the bottom of the loop.
• A do...while loop is similar to a while loop, except that a do...while loop is
guaranteed to execute at least one time.

do {
statement(s);
}while( condition );
#!/usr/local/bin/perl
$a = 10;
# do...while loop execution
do{
print "Value of a: $a\n”;
$a = $a + 1;
}while( $a < 20 );
Perl nested Loop
• A loop can be nested inside of another loop. Perl allows to nest all type of loops to
be nested.
Loop Control Statements
• Loop control statements change the execution from its normal
sequence.

Sr.No. Control Statement & Description


next statementCauses the loop to skip the remainder of its
1
body and immediately retest its condition prior to reiterating.
last statementTerminates the loop statement and transfers
2
execution to the statement immediately following the loop.
continue statementA continue BLOCK, it is always executed
3
just before the conditional is about to be evaluated again.
redo statementThe redo command restarts the loop block
4 without evaluating the conditional again. The continue block, if
any, is not executed.
goto statementPerl supports a goto command with three
5
forms: goto label, goto expr, and goto &name.
The Infinite Loop
• A loop becomes infinite loop if a condition never becomes false.
• The for loop is traditionally used for this purpose.
• Since none of the three expressions that form the for loop are required, you can
make an endless loop by leaving the conditional expression empty.

#!/usr/local/bin/perl
for( ; ; ) {
printf "This loop will run forever.\n";
}

• You can terminate the above infinite loop by pressing the Ctrl + C
keys.
Perl - Subroutines

• A Perl subroutine or function is a group of statements that together


performs a task.
• You can divide up your code into separate subroutines. How you divide up
your code among different subroutines is up to you, but logically the
division usually is so each function performs a specific task

Define and Call a Subroutine


• The general form of a subroutine definition in Perl programming language
is as follows

sub subroutine_name {
body of the subroutine }
• The typical way of calling that Perl subroutine is as follows −
subroutine_name( list of arguments );
&subroutine_name( list of arguments );
EXAMPLE:
#!/usr/bin/perl

# Function definition
sub Hello {
print "Hello, World!\n";
}

# Function call
Hello();
Passing Arguments to a Subroutine
Passing Lists to Subroutines
Passing Hashes to Subroutines
• When you supply a hash to a subroutine or operator that accepts a list, then
hash is automatically translated into a list of key/value pairs.
Returning Value from a Subroutine
Private Variables in a Subroutine
• By default, all variables in Perl are global variables, which means they can be
accessed from anywhere in the program.
• But you can create private variables called lexical variables at any time
with the my operator.
• The my operator confines a variable to a particular region of code in which it
can be used and accessed.
• Outside that region, this variable cannot be used or accessed. This region is
called its scope.
• lexical scope is usually a block of code with a set of braces around it, such as
those defining the body of the subroutine or those marking the code blocks
of if, while, for, foreach, and eval statements.

sub somefunc {
my $variable; # $variable is invisible outside somefunc()
my ($another, @an_array, %a_hash); # declaring many variables at once
}
Temporary Values via local()
• The local is mostly used when the current value of a variable must be
visible to called subroutines. A local just gives temporary values to global
(meaning package) variables. This is known as dynamic scoping.
Perl - File I/O

• The basics of handling files are simple: you associate a filehandle with an
external entity (usually a file) and then use a variety of operators and
functions within Perl to read and update the data stored within the data
stream associated with the filehandle.
• 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
• Three basic file handles are - STDIN, STDOUT, and STDERR, which
represent standard input, standard output and standard error devices
respectively.
Opening and Closing Files
Open Function
• Following is the syntax to open file.txt in read-only mode. Here less than < sign
indicates that file has to be opend in read-only mode.

open(DATA, "<file.txt");

• Here DATA is the file handle, which will be used to read the file.

#!/usr/bin/perl
open(DATA, "<file.txt") or die "Couldn't open file file.txt, $!";
while(<DATA>) {
print "$_"; }
• Following is the syntax to open file.txt in writing mode. Here less than > sign
indicates that file has to be opend in the writing mode.

open(DATA, ">file.txt") or die "Couldn't open file file.txt, $!";


open (FH, ‘>’, “filename.txt”);
• This example actually truncates (empties) the file before opening it for writing,
which may not be the desired effect. If you want to open a file for reading and
writing, you can put a plus sign before the > or < characters.

open(DATA, "+<file.txt"); or die "Couldn't open file file.txt, $!";

• To truncate the file first −

open(DATA, "+>file.txt"); or die "Couldn't open file file.txt, $!";

• A double >> opens the file for appending, placing the file pointer at the end,
so that you can immediately start appending information. However, you can't
read from it unless you also place a plus sign in front of it

open(DATA, "+>>file.txt"); or die "Couldn't open file file.txt, $!";


Sr.No. Entities & Definition
< or r
1
Read Only Access
> or w
2
Creates, Writes, and Truncates
>> or a
3
Writes, Appends, and Creates
+< or r+
4
Reads and Writes
+> or w+
5
Reads, Writes, Creates, and Truncates
+>> or a+
6
Reads, Writes, Appends, and Creates

Close Function
• To close a filehandle, and therefore disassociate the filehandle from the
corresponding file, you use the close function
close FILEHANDLE
close(DATA) || die "Couldn't close file properly";
The <FILEHANDL> Operator
• The main method of reading the information from an open filehandle is the
<FILEHANDLE> operator. In a scalar context, it returns a single line from the
filehandle.

• When you use the <FILEHANDLE> operator in a list context, it returns


a list of lines from the specified filehandle. For example, to import all
the lines from a file into an array −
Copying Files
Renaming a file
• Here is an example, which shows how we can rename a file file1.txt to file2.txt.

Deleting an Existing File


• Here is an example, which shows how to delete a file file1.txt using
the unlink function.

if (-e $file) --- used to check file existance , my


file = “file1.txt”.
THANK YOU

You might also like