S. L Unit - Iii
S. L Unit - Iii
S. L Unit - Iii
Origin of scripting:
The use of the word 'script' in a computing context dates back to the early 1970s, when
the originators of the UNIX operating system create the term 'shell script for sequence of
commands that were to be read from a file and follow in sequence as if they had been typed in
at the keyword. e.g. an 'AWKscript', a 'perl script' etc., the name 'script' being used for a text
file that was intended to be executed directly rather than being compiled to a different form of
file prior to execution.
Other early occurrences of the term 'script' can be found. For example, in a DOS-based
system, use of a dial-up connection to a remote system required a communication package that
used proprietary language to write scripts to automate the sequence of operations required to
establish a connection to a remote system.
Note that if we regard a scripts as a sequence of commands to control an application or
device, a configuration file such as a UNIX 'make file' could be regard as a script.
However, scripts only becomes interesting when they have the added values that comes from
using programming concepts such as loops and branches.
Scripting today:
SCRIPTING IS USED WITH 3 DIFFRENT MEANINGS:
1. A new style of programming which allows applications to be developed much faster than
traditional methods allow, and maks it possible for applications to evolve rapidly to meet
changing user requirements. This style of programming frequently uses a scripting language to
interconnect off the shelf components that are themselves written in conventional language.
Applications built in this way are called 'glue applications and the language is called a 'glue
language'.
2. Using a scripting language to manipulate, customize and automate the facilities of an existing
system' as the ECMAScript definition puts it. Here the script is used to control an application
that privides a programmable interface: this may be an API, though more commonly the
application is construted from a collection of objects whose properties and methods are exposed
to the scripting language. Example: use of Visual Basic for applications to control the
applications in the Microsoft Office Suite..
3. Using a scripting language with its rich funcationaliy and case of use as an alternate to a
conventional language for general programming tasks particularly system programming and
administration. Examples: are UNIX system. adminstrators have for a long time used scripting
languages for system maintenace tasks, and administrators of WINDOWS NT systems are
adopting a scripting language PERL for their work.
Integrated compile and run: SL's are usually characterized as interpreted languages,
but this is just an oversimplification. They operate on an immediate execution, without
need to issue separate command to compile the program and then to run the resulting
object file, and without the need to link extensive libraries into he object code. This is
done automatically. A few SL'S are indeed implemented as strict interpreters.
Low overheads and ease of use:
1. Variables can be declared by use
2. The number of different data types is usually limited
3. Everything is string by context it will be converted as number(vice versa) 4.number
of data structures is limited(arrays)
Enhanced functionality: SL's usually have enhanced functionality in some. areas. For
example most languages provide string manipulation based on the use of regular
expressions, while other languages provide easy access to low- level operating system
facilities, or to the API, or object exported by an application.
Efficiency is not an issue: Ease of use is achieved at the expense of efficiency, because
efficiency is not an issue in the applications for which
A scripting language is usually interpreted from source code or bytecode. By contrast,
the software environment the scripts are written for is typically written in a compiled
language and distributed in machine code form.
Scripting languages may be designed for use by end users of a program - end- user
development or may be only for internal use by developers, so they can write portions
of the program in the scripting language.
Scripting languages typically use abstraction, a form of information hiding. to spare
users the details of internal variable types, data storage, and memory management.
Scripts are often created or modified by the person executing them, but they are also
often distributed, such as when large portions of games are written. in a scripting
language.
The characteristics of case of use,particularly the lack of an explicit compile-link-load
sequence, are sometimes taken as the sole definition of a scripting language.
Web scripting:
Web is the most fertile areas for the application of scripting languages.
Web scripting divides into three areas
1. processing forms
2. creating pages with enhanced visual effects and user interaction and
3. Generating pages 'on the fly' from material held in database.
Processing Web forms:
In the original implementation of the web, when the form is submitted for processing,
the information entered by the user is encoded and sent to the server for processing by
a CGI script that generates an HTML page to be sent back to the Web browser.
This processing requires string manipulation to construct the HTML page that
constitutes the replay, and may also require system access, to run other processes and
to establish network connections. Perl is also a language that uses CGI scripting.
Alternatively for processing the form with script running on the server it possible to do
someclient-side processing within the browser to validate form data before sending it
to the server by using JavaScript, VBScript etc.
Dynamic Web pages:
'Dynamic HTML' makes every component of a Web page (headings, anchors, tables etc.) a
scriptable object. This makes it possible to provide simple interaction with the user using scripts
written in JavaScript/Jscript or VBScript, which are interpreted by the browser.
Microsoft's ActiveX technology allows the creation of pages with more claborate user
interaction by using embedded visual objects called ActiveX controls. These controls are
scriptable objects, and can in fact be scripted in a variety languages. This can be scripted by
using Perl scripting engine.
Dynamically generated HTML:
Another form of dynamic Web page is one in which some or all of the HTML is generated by
scripts executed on the server. A common application of the technique is to construct pages
whose content is retrieved from a database. For example, Microsoft's IIS web server
implements Active Server Pages (ASP), which incorporate scripts in Jscript or VBScript.
The universe of scripting languages:
Scripting can be traditional or modern scripting, and Web scripting forms an important
part of modern scripting. Scripting universe contains multiple overlapping worlds:
The original UNIX world of traditional scripting using Perl and Tel The Microsoft
world of Visual Basic and Active controls
The world of VBA for scripting compound documents the world of client-side and
server-side Web scripting.
The overlap is complex, for example web scripting can be done in VBScript, JavaScript/Jscrint.
Perl or TCL. This universe has been enlarged as Perl and The Microsoft world of Visual Basic
and Active controls The world of VBA for scripting compound documents the world of client-
side and server-side Web scripting.
The overlap is complex, for example web scripting can be done in VBScript,
JavaScript/Jscript, Perl or Tcl. This universe has been enlarged as Perl and Tel are used to
implement complex applications for large organizations e.g Tcl has been used to develop a
major banking system, and Perl has been used to implement an enterprise- wide document
management system for a leading aerospace company.
Whitespaces in Perl
A Perl program does not care about whitespaces. Following program works perfectly fine---
#!/usr/bin/perl
print "Hello, world\n":
But if spaces are inside the quoted strings, then they would be printed as is. For
example -
#!/usr/bin/perl
#This would print with a line break in the middle
print "Hello world\n";
This will produce the following result-
Hello
#This would print with a line break in the middle
print "Hello
world\n";
This will produce the following result -
Hello world
All types of whitespace like spaces, tabs, newlines, etc. are equivalent for the interpreter when
they are used outside of the quotes. A line containing only whitespace, possibly with a
comment, is known as a blank line, and Perl totally ignores it.
Single and Double Quotes in Perl:
You can use double quotes or single quotes around literal strings as follows -
#!/usr/bin/perl
print "Hello, world\n";
print 'Hello, world\n';
This will produce the following result -
Hello, world
Hello, world\n$
There is an important difference in single and double quotes. Only double. quotes interpolate
variables and special characters such as newlines \n. whereas single quote does not interpolate
any variable or special character. Check below example where we are using Sa as a variable to
store a value and later printing that value
#!/usr/bin/perl
$a = 10;
print "Value of a = Sa\n";
print 'Value of a = Sa\n';
This will produce the following result -
Value of a 10
Value of a Sain$
"Here" Documents
You can store or print multiline text with a great comfort. Even you can make use of variables
inside the "here" document. Below is a simple syntax, check carefully there must be no space
between the << and the identifier.
An identifier may be either a bare word or some quoted text like we used EOF below. If
identifier is quoted, the type of quote you use determines the treatment of the text inside the
here docoment, just as in regular quoting. An unquoted identifier works like double quotes.
#!/usr/bin/perl
$a = 10: $var=<<"EOF";
This is the syntax for here document and it will continue until it encounters a EOF in the first
line. This is case of double quote so variable value will be interpolated. For example value of
a = $a FOF
print "$var\n";
$var = <<EOF': This is case of single quote so variable value will be interpolated. For example
value of a = $a FOF print "$var'n":
This will produce the following result -
This is the syntax for here document and it will continue until it encounters a EOF in
the first line. This is case of double quote so variable value will be interpolated. For
example value of a = 10.
This is case of single quote so variable value will be interpolated. For example value of
a = Sa
Escaping Characters
Perl uses the backslash (1) character to escape any type of character that might interfere with
our code. Let's take one example where we want to print double quote and S sign -
#!/usr/bin/perl
$result = "This is \"number""; print "$result\n";
print "\Sresult\n":
This will produce the following result -
This is "number"
$result
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 S. @ 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 $Manpower and $manpower are two
different identifiers in Perl.
Perl is a loosely typed language and there is no need to specify a type for your data
while using in your program. The Perl interpreter will choose the type based on the
context of the data itself.
Perl has three basic data types: scalars, arrays of scalars, and hashes of scalars. also
known as associative arrays. Here is a little detail about these data types.
S. Types & Description:
No.
1 Scalar
Scalars are simple variables. They are preceded by a dollar sign (S). A
scalar is a number, a string, or a reference. A reference is actually an
address of a variable, which we will see in the upcoming chapters.
2 Arrays
Arrays are ordered lists of scalars that you access with a numeric index.
which starts with 0. They are preceded by an "at" sign (@).
3 Hashes
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 2000
Scientific 16.12E14
Hexadecimal Oxffff
Octal 0577
String Literals
Strings are sequences of characters. They are usually alphanumeric values. delimited by either
single (') or double (") quotes. They work much like UNIX shell quotes where you can use
single quoted strings and double quoted strings.
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).
You can embed newlines or any of the following Escape sequences directly in your double
quoted strings –
Escape sequence Meaning
\\ Backslash
\" Single quote
La Double quote
\b Alert or bell
\f Backspace
\n Form feed
\r Newline
\t Carriage return
\v Horizontal tab
\0nn Horizontal tab
\xnn
\cX
\u
\l
example
Let's see again how strings behave with single quotation and double quotation. Here we will
use string escapes mentioned in the above table and will make use of the scalar variable to
assign string values.
#!/usr/bin/perl
#This is case of interpolation. $str = "Welcome to \ntutorialspoint.com!"; print "$str\n":
# This is case of non-interpolation. $str = 'Welcome to \ntutorialspoint.com!"; print "$str\n";
#Only W will become upper case. $str = "uwelcome to tutorialspoint.com!"; print "$strin":
#Whole line will become capital. $str = "\UWelcome to tutorialspoint.com!"; print "$str\n";
# A portion of line will become capital. $str = "Welcome to \Ututorials point\E.com!"; print
"$str\n";
#Backsalash non alpha-numeric including spaces. $str = "\QWelcome to tutorialspoint's
family": print "$str\n";
This will produce the following result-
Welcome to
tutorialspoint.com!
Welcome to \ntutorialspoint.com!
Welcome to tutorialspoint.com!
WELCOME TO TUTORIALSPOINT.COM!
Welcome to TUTORIALSPOINT.com!
Welcome to tutorialspoint\'s family
Names and Values in Perl:
Names:
Like any other programming language, Perl manipulates variables which have a name
(or identifier) and a value: a value is assigned to a variable by an assignment statement
of the form name=value:
Variable names resemble nouns in English, and like English, Perl distinguishes between
singular and plural nouns. A singular name is associated with a variable that holds a
single item of data (a scalar value), a plural name is associated with a variable that holds
a collection of data items (an array or hash).
If we write an assignment, eg. jj+1, the occurance of j on the left denotes a storage
location, whilw the right-hand occurance denotes the contents of the storage location.
We sometimes refer to these as the Ivalue and rvalue of the variable: more precisely we
are determining the meaning of the identifier in a left-context or a right- context. In the
assignment a[j] = a[j] + 1, both occurances of j are determined in a right-context, even
though one of them appears on the left of the assignment.
In conventional programming languages, new variables are introduced by a declaration,
which specifies the name of the new variable and also its type, which determines the
kind of value that can be stored in the variable and, by implication, the operations that
can be carried out on that variable..
Scalar data: Strings and numbers:
In common with many scripting languages, Perl recognizes just two kinds of scalar data: strings
and numbers. There is no distinction between interger and real numbers as different types.Perl
is a dynamically typed language: the system keeps track of whether a variable contains a
numeric value or a string value, and the user doesn't have to worry about thedifference between
strings and numbers since conversions between the two kinds of data are done automatically
as required by the context in which they are used.
Boolean values:
All programming languages need some way of representing truth values and Perl is no
exception. Since scalar values are either numbers or strings, some convention is needed for
representing Boolean values, and Perl adopts the simple rule that numeric zero. "0" and the
empty string ("") mean false, and anything else means truc.
Numeric constants:
Numeric constants can be written in a variety of ways, including specific notation, octal and
hexadecimal. Although Perl tries to emulate natural human communication, the common
practice of using commas or spaces to break up a large integer constant into meaningful digit
groups cannot be used, since the comma has a syntactic significance in Perl. Instead,
underscores can be included. in a number literal to improve legibility.
String constants:
String constants can be enclosed in single or double quotes. The string is terminated by the first
next occurance of the quote which started it, so a single-quoted string can include double quotes
and vice versa. The q (quote) and qq (double quote) operators allow you to use any character
as a quoting character. Thus q/any string orq (any string) are the same as 'any string' and qq/any
string / or qq (any string) are the same as "any string"
Assignment:
Borrowing from C. Perl uses '=' as the assignment operator. It is important to note that an
assignment statement returns a value, the value assigned. This permits statements like Sb4+(Sa
= 3);
which assigns the value 3 to $a and the value 7 to $b.If it is required to interpolate a variable
value without an intervening space the following syntax, borrowed from UNIX shell scripts, is
used: Sa = "Java:
Sb = "Sa Script"; which gives $b the value "JavaScript".
<STDIN> - a special value:
When the 'variable' <STDIN> appears in a context where a scalar value is required, it evaluates
to a string containing the next line from standard input, including the terminating newline. If
there is no input queued, Perl will wait until a line is typed and the return keypressed. The
empty string is treated as false in a Boolean context. If <STDIN> appears on the right-hand
side of an assignment to a scalar variable, the string containing the input line is assigned to the
variable named on the eft. If it appears in any other scalar context the string is assigned to the
anonymous variable: this can be accessed by the name $ many operations use it as a default.
Scalar Expressions:
Scalar data items are combined into expressions using operators. Perl has a lot of operators,
which are ranked in 22 precedence levels. These are carefully chosen so that the 'obvious"
meaning is what You get, but the old advice still applies: if in doubt,use brackets to force the
order of evaluation. In the following sections we describe the available operators in their natural
groupings-arithmetic. strings, logical etc.
Arithmetic operators:
Following the principles of 'no surprises' Perl provides the usual
Arithmetic operators, including auto-increment and auto-decrement operators after the manner
of C: note that in Sc=17: $d++$c:
The sequence is increment and the assign, whereas in Sc=17; $d = $c++;
The sequence is assign then increment. As C, binary arithmetic operations can be combined
with assignment, e.g. Sa += 3:
This adds 3 to Sa, being equivalent to Sa=$a+3;
As in most other languages, unary minus is used to negate a numeric value; an almost never-
used unary plus operator is provided for completeness.
String Operators
Perl provides very basic operators on strings: most string processing is one using built-in
functions expressions, as described later.
Unlike many languages use as a concatenation operator for strings, Perl uses a period for this
purpose: this lack of overloading means that an operator uniquely determines the context for
its operands.
The other string operator is x, which is used to replicate strings, e.g.
Sa-"Hello" x 3;
The capability of combining an operator with assignment is extended to string operations. E.g.
Sets Sa to "Hello Hello Hello".Sfoo"":
Appends a space to $foo.
So far, things have been boringly conventional for the most part. However, we begin to get a
taste of the real flavor of perl when we see how it adds a little magic when some operators,
normally used in arithmetic context, are used in a string context.
Two examples illustrate this.
1.Auto increment:
If a variable has only ever been used in a string context, the auto increment operator can be
applied to it. If the value consists of a sequence of letters, or a sequence of letters followed by
a sequence of digits, the auto increment takes place in string mode starting with the rightmost
character, with 'carry' along the string. For example, the sequence
Saa0'; $b='Az9';
Print ++Sa,, ++Sb: "/n": Prints al Ba0.
2. Unaryminus:
This has an unusual effect on non numeric values. Unary minus applied to a string which starts
with a plus or minus character returns the same string, but starting with the opposite sign. Unary
minus applie to an identifier returns a string consists of minus prefixed to the characters of the
identifiers. Thus if we have a variable named Sconfig with the value "foo", then-config
evaluates the string *"- foo". This is useful, for example, in constructing command arguments
are introduced by -
Comparison operators:
The value of comparisons is returned as 1 if true, and an empty string ("") if false, in accordance
with the convention described earlier.
Two families of comparison operators provide, one for numbers and one for strings. The
operator used determines the context, and perl converts the operands as required to match the
operator.
This duality is necessary because a comparison between strings made up entirely numerical
digits should apply the usual rules for sorting strings ASCII as a collating sequence, and this
may not give the same result as the numerical comparison('5' <'10') returns the value true as a
numerical comparison having been converted into (5<10) where as the string comparison ('5'
It '10') returns false, since 10 comes before 5 in the canonical sort order for ASCII strings.
The comparison operator ( for numbers, cmp for strings), performs a three way test, returning
-1 for less-than, 0 for equal an +1 for greater-than.
Note that the comparison operators are non associative, so an expression like
Sa > $b > Sc Is erroneous
logical operators:
The logical operators allows to combine conditions using the usual logical operations 'not'(!,
not), 'and' (&&,and) and 'or'(,or). Perl implements the 'and' and 'or' operators in "shortcut' mode,
Le evaluation stops as soon as the final result is certain using the rules false &&b=false, and
true||b=true.
Before Perl 5,only the !, && and || operators were provided. The new set, not, and, or, are
provided partly to increase readability, and partly mit
Bitwise operators:
The unary tilde(-) applied to a numerical argument performs bitwise. negation on its operand,
generating the one's compliment. If applied to a string operand it complements all the bits in
the string - effective way of inverting a lot of bits. The remaining bitwise operators & (and), |
(or) and (exclusive or)- have a rather complicated definition. If either operand is a number or a
variable that has previously been used as a number, both operands are converted to integers if
need be, and the bitwise operation takes place between the integers. If the both operands are
strings, and if variables have never been used as numbers. Perl performs the bitwise operation
between corresponding bits in the two strings, padding the shorter strings with zeros as
required.
Conditional expressions:
A conditional expression is one whose values is choosen from two alternatives at run-time
depending on the outcome of a test. The syntax is borrowed from C:
Test? true_exp: false_exp
The first expression is evaluated as Boolean value if it returns true the whole expression is
replaced by true_exp,otherwise it is replaced by false_exp. e.g.
$a= (Sa<0)? 0: $a;
Conditional Statement
A Perl if statement consists of a boolean expression followed by one or more statements.
Syntax
The syntax of an if statement in Perl programming language is –
if(boolean expression)
{
#statement(s) will execute if the given condition is true
}
If the boolean expression evaluates to true then the block of code inside the if statement will
be executed. If boolean expression evaluates to false then the first set of code after the end of
the if statement (after the closing curly brace) will be executed.
Flow Diagram
If condition is true
Conditio
n
If condition
Is true Conditional code
Example
#!/usr/local/bin/perl
$a 10:
#check the boolean condition using if statement
if( Sa 20) (
#if condition is true then print the following
printf "a is less than 20\n";
print "value of a is: $a\n":
$a="
#check the boolean condition using if statement
if($a)
#if condition is true then print the following
printf "a has a true value\n";
print "value of a is: Sa\n":
First IF statement makes use of less than operator (<), which compares two operands and if
first operand is less than the second one then it returns true otherwise it returns false. So when
the above code is executed, it produces the following result –
a is less than 20
value of a is : 10
value of a is:
A Perl if statement can be followed by an optional else statement, which executes when the
boolean expression is false.
Syntax
The syntax of an if...else statement in Perl programming language is -
if(boolean_expression)
{
#statement(s) will execute if the given condition is true
} else {
#statement(s) will execute if the given condition is false
}
If the Boolean expression evaluates to true, Then the if block of code will be executed
otherwise else block of code will be executed.
The number 0, the strings '0' and "", the empty list (), and undef are all false in a boolean context
and all other values are true. Negation of a true value by ! or not returns a special false value.
Flow Diagram:
If condition is true
Condition
If condition
Is false If code
else code
Example
#!/usr/local/bin/perl
$a = 100;
#check the boolean condition using if statement
if($a <20) # if condition is true then print the following
printf "a is less than 20\n"; else
# if condition is false then print the following printf "a is greater than 20\n";
print "value of a is: $a\n";
$a="":
# check the boolean condition using if statement
if($a)
# if condition is true then print the following printf "a has a true value\n";
else {
#if condition is false then print the following printf ""
print "value of a is: Sa\n";
expression
Case 1
Code block 1
Case 2
Code block2
default
Code block N
Example
#!/usr/local/bin/perl
use Switch:
$var = 10:
@array = (10, 20, 30):
%hash = ('key l' => 10, 'key2' => 20);
switch($var) {
case 10 { print "number 100\n" }
case 10 case "a" { print “string a” }
case [1..10,42] { print "number in list" }
case (\@array) { print "number in list" }
case (%hash) { print "entry in hash" }
else { print "previous case not true"}
When the above code is executed, it produces the following result- number 100
Perl Loops (for, foreach, while, do... while, until, Nested loops) Looping in programming
languages is a feature which facilitates the execution of a set of instructions or functions
repeatedly while some condition evaluates to true. Loops make the programmers task simpler.
Perl provides the different types of loop to handle the condition based situation in the program.
The loops in Perl are:
for Loop
"for" loop provides a concise way of writing the loop structure. Unlike a while loop, a for
statement consumes the initialization, condition and increment/decrement in one line thereby
providing a shorter, easy to debug structure of looping.
Syntax:
for (init statement; condition; increment/decrement)
{
#Code to be Executed
Increment
Flow Chart:
Decrement
de
If True
Condition
CStart
Initialization
checking
If false
End
A for loop works on a predefined flow of control. The flow of control can be determined by
the following:
Init Statement: This is the first statement which is executed. In this step, we initialize a
variable which controls the loop.
condition: In this step, the given condition is evaluated and the for loop runs if it is True. It is
also an Entry Control Loop as the condition is checked prior to the execution of the loop
statements.
Statement execution: Once the condition is evaluated to true, the statements in the loop body
are executed.
Increment/Decrement: The loop control variable is changed here (incremented or
decremented) for updating the variable for next iteration. Loop termination: When the
condition becomes false, the loop terminates marking the end of its life cycle.
Loop termination: When the condition becomes false , the loop terminate making the end of
its life cycle.
Example:
# Perl program to illustrate
# the for loop
for (Scount=1; $count <=3; $count++)
}
# for loop
print "Scripting Language \n"
Output:
Scripting Language
Scripting Language
Scripting Language
Foreach Loop
A foreach loop is used to iterate over a list and the variable holds the value of the elements of
the list one at a time. It is majorly used when we have a set of data in a list and we want to
iterate over the elements of the list instead of iterating over its range. The process of iteration
of each element is done automatically by the loop.
Syntax: foreach variable
{
#Code to be Executed
} List
Flow Chart:
Next
Element
false
Code to be execution
Example:
Perl
# Perl program to illustrate
# the foreach loop
# Array @data = ('script'. 'FOR', 'perl');
# foreach loop
foreach $word (@data)
print $word }
Output:
scriptFORperl
while Loop
A while loop generally takes an expression in parenthesis. If the expression is True then the
code within the body of while loop is executed. A while loop is used when we don't know the
number of times we want the loop to be executed however we know the termination condition
of the loop. It is also known as a entry controlled loop as the condition is checked before
executing the loop. The while loop can be thought of as a repeating if statement.
Syntax:
while (condition)
{ #Code to be executed
Flow Chart:
If true
Start Condition Statement
Checking
If false
Example:
Perl
# Perl program to illustrate
# the while loop
# while loop
$count = 3;
while ($count >= (0)
{
$count = $count - 1:
print "Scripting Language \n";
}
Output:
Scripting Language
Scripting Language
Scripting Language
Scripting Language
Infinite While Loop: While loop can execute infinite times which means there is no
terminating condition for this loop. In other words, we can say there are some conditions which
always remain true, which causes while loop to execute infinite times or we can say it never
terminates.
Example: Below program will print the specified statement infinite time and also give the
runtime error as Output Limit Exceeded on online IDE
Perl
#Perl program to illustrate
#the infinite while loop
#infinite while loop
#containing condition 1
# which is always true
while(1)
print "Infinite While Loop\n"; }
Output:
Infinite While Loop
Infinite While Loop
Infinite While Loop
Infinite While Loop
.
.
.
.
.
do.... while loop
A do.. while loop is almost same as a while loop. The only difference is that do..while loop
runs at least one time. The condition is checked after the first execution. A do..while loop is
used when we want the loop to run at least one time. It is also known as exit controlled loop
as the condition is checked after executing the loop.
Syntax:
do {
#statements to be Executed
} while(condition);
Flow Chart:
start
Condition
statement checking
if false
end
Example:
Perl
#Perl program to illustrate
#do..while Loop
$a = 10;
#do.. While loop
do {
print "$a";
$a = $a 1: } while ($a > 0);
Output:
10 9 8 7 6 5 4 3 2 1
Until loop
until loop is the opposite of while loop. It takes a condition in the parenthesis and it only runs
until the condition is false. Basically, it repeats an instruction or set of instruction until the
condition is FALSE. It is also entry controller loop i.e. first the condition is checked then set
of instructions inside a block is executed.
Syntax:
until (condition)
#Statements to be executed
}
Flow Chart:
If false
start Condition Statememt
checking
if true
Example:
Perl
# Perl program to illustrate until Loop
$a = 10;
# until loop until ($a < 1)
print "$a"; $a = $a - 1;
Output: 10 98 7 6 5 4 3 2 1
Nested Loops
A nested loop is a loop inside a loop. Nested loops are also supported by Perl Programming.
And all above-discussed loops can be nested.
Syntax for different nested loops in Perl:
Nested for loop
for (init statement; condition; increment/decrement)
{
for (init statement; condition; increment/decrement)
#Code to be Executed
}
}
Nested foreach loop
foreach variable_1 (@array_1)
{
foreach variable_2 (@array_2)
{
#Code to be Executed
}
}
Nested while loop
while (condition)
{
while (condition)
{
#Code to be Executed
}
}
Nested do..while loop
do {
do {
#Code to be Executed
} while(condition)
} while(condition);
Nested until loop
until (condition) {
until (condition)
{
#Code to be Executed
}
}
Example:
Perl
# Perl program to illustrate
# nested while Loop
$a = 5:
$b=0;
# outer while loop
while (\$a<7)
{ Sh=0
# inner while loop
while ($b <7)
{
print "value of a = $a, b = $b\n";
$b=Sb+1
$a = $a + 1;
print "Value of a = $a\n\n";
Output:
value of a = 5. b=0
value of a = 5, b =1
value of a=5. b=2
value of a 5. b=3
value of a=5. b=4
value of a=5, b=5
value of a = 5, b=6
Value of a=6
value of a=6 b=0
value of a=6. b=1
value of a=6. b=2
value of a = 6, b=3
value of a=6,b=4
value of a=6 b = 5
value of a=6~h=6
Value of a=7
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.
Here is a simple example of using the array variables
#!/usr/bin/perl
@ages (25, 30, 40);
@names = ("John Paul", "Lisa", "Kumar");
print "\Sages[0] = Sages[0]\n";
print "\$ages[1] = Sages[1]\n"; print "\Sages[2] = Sages[2]\n";
print "\Snames[0] = $names[0]\n":
print "\Snames[1] = $names[1]\n";
print "\Snames[2] = $names[2]\n";
this will produce the following result -
Sages[0] = 25
Sages[1] = 30
Sages[2] = 4
Snames[0] = John Paul
$names[1] = Lisa
$names[2] = Kumar
How to define array?
Arrays are prefixed with @ sign. This is how you define an array
@friends = ("Ajeet", "Chaitanya", "Rahul");
This is the array of strings that holds three strings. Another way of doing the same is:
@friends = qw(Ajeet Chaitanya Rahul); #same as above
Note: qw stands for quoted words, by using qw you can avoid the quote marks and you type
less.
While learning Perl, you may come accross few examples, where you see the following kind
of array definition:
@friends = qw/Ajeet Chaitanya Rahul/; #same as above
This is because Perl lets you choose any punctuation character as delimiter.
All the following statements are same:
@friends = qw/Ajeet Chaitanya Rahul/; #same as above This is because Perl lets you choose
any punctuation character as delimiter.
All the following statements are same:
@friends = qw/Ajeet Chaitanya Rahul/;
@friends = qw! Ajeet Chaitanya Rahul!; @friends = qw;
@friends = qw{Ajeet Chaitanya Rahul);
@friends = qw[Ajeet Chaitanya Rahul];
Note: The opening and closing delimiter must be same.
Access array element
You must have used arrays in another programming langauge like C, C++, Java etc. The basic
concept of array is same here. Lets take an example to understand how to define an array and
how to access the elements of it.
#!/usr/bin/perl
@friends = ("Ajeet", "Chaitanya", "Rahul");
print "\Sfriends[0] = $friends[0]\n";
print "\$friends[1] = $friends[1]\n";
print "\Sfriends[2] = $friends[2]\n";
Output:
$friends[0] = Ajeet
$friends[1] = Chaitanya
$friends[2] = Rahul
As you can see in the above program that arrays are prexied with @symbol. Since, individual
array elements are nothing but scalars, they are prexied with $ symbol.
Range operator
Range operator is denoted by double dots "..". This operator is used for creating sequential lists.
For example:
#!/usr/bin/perl
@num = (3..9); # same as (3, 4, 5, 6, 7, 8, 9)
foreach Stemp (@num) {
print "Stemp\n"
Output:
foreach Stemp (@num) { print "Stemp\n";
}
Output:
3
4
5
3
5
6
8
9
Lets take few more examples to understand the range operator:
(2.9..7.9) # same as (2, 3, 4, 5, 6, 7), values after decimal are truncated
(9..3) # empty list, only works in increasing order
(1, 3..6, 10, 12..14) # same as (1, 3, 4, 5, 6, 10, 12, 13, 14),
Operators:
pop and push : pop operator removes the last element from an array and returns it. Lets take
an example to understand how pop operator works:
#!/usr/bin/perl
@num = (3..7); # same as (3, 4, 5, 6, 7)
$n1 = pop(@num); # Sn1 is 7, array is (3, 4, 5, 6)
$n2 = pop(@num); # Sn2 is 6, array is (3, 4, 5)
print "\$n1 is: $n1\n";
print "\Sn2 is: $n2\n";
print "array now has:\n";
foreach $temp (@num) {
print "Stemp\n"
}
pop @num; # 5 is discarded, array is (3, 4)
print "array now has:\n";
foreach Stemp (@num) {
print "Stemp\n";
} Output:
Snl is: 7
$n2 is: 6
array now has:
3
4
5
25G
60%
array now has:
3
4
push operator adds an element to the end of the array.
Example:
#!/usr/bin/perl
@num = (10..12); # same as (10, 11, 12)
push (@num, 9); # array is (10, 11, 12, 9)
push (@num, 6); # array is (10, 11, 12, 9,6)
print "array now has:\n";
foreach Stemp (@num) {
print "Stemp\n";
@num2 = (11, 22, 33);
push (@num, @num2); # adding another array to the end
print "array now has:\n"
foreach $temp (@num)
print "Stemp\n";
Output:
array now has:
10
11
12
9
6
array now has:
10
11
12
9
6
11
22
33
Operators: shift and unshift
As we have seen above that push and pop operators does the adding and removing at the end
of the array. The shift and unshift performs operation at the beginning of the array.
shift operator:
shift operator works similar to pop operator, however unlike pop operator it performs the
operation at the beginning of the array.
#!/usr/bin/perl
@num = (3..7); # same as (3, 4, 5, 6, 7)
Sn1 = shift(@num); # Snl is 3, array is (4, 5, 6, 7)
$n2 = shift(@num); # Sn2 is 4, array is (5,6, 7)
print "\Sn1 is: $nl\n";
print "\$n2 is: $n2\n";
print "array now has:\n";
foreach Stemp (@num) {
print "Stemp\n";
}
shift @num; #5 is discarded, array is (6, 7)
print "array now has:\n";
foreach Stemp (@num) {
print "Stemp\n";
Output:
Sn1 is: 3
Sn2 is: 4
array now has:
5
6
7
array now has:
6
7
unshift operator:
unshift operator works similar to push operator, however unlike push operator it performs the
operation at the beginning of the array.
#!/usr/bin/perl
@num = (10..12); # same as (10, 11, 12)
unshift (@num, 9); # array is (9, 10, 11, 12)
unshift (@num, 6); # array is (6, 9, 10, 11, 12)
print "array now has:\n";
foreach Stemp (@num) {
print "Stemp\n";
}
@num2 = (11, 22, 33);
unshift (@num, @num2); # adding another array to the beginning
print "array now has:\n"; foreach Stemp (@num) {
print "Stemp\n";
}
output:
array now has:
6
9
10
11
12
array now has:
11
2
33
6
9
10
1
12
Splice operator
In the above section we learnt how to perform push, pop, shift and unshift operation on array.
However there is a limitation with these operators, they only perform either on the beginning
of the array or at the end of the array. What if
syntax:
splice @array_name, s. 1, @another_arra
The splice operator can take upto four arguments.
First argument is array name, here we specify the array on which we are performing operation
second argument is starting point, as I said above, you can perform the opeartion in the middle
of the array. This specifies the starting point of the operation.
Third argument is the length
fourth argument is another list or array.
Lets take few examples to understand this:
Example 1: Only two arguments in splic
@myarray = qw(Rahul, Joe, Ajeet, Tim, Lisa);
@myvar = splice @array, 2
#removes everything after Aject
# @myarray is qw(Rahul, Joe, Ajeet)
#@myvar is qw(Tim, Lisa)
Third and fouth argument of splice operatorare optional. In the above example, we have only
provided two arguments, array and starting point. Similar to array, the index of splice operator
starts at (), which means Ajeet is the starting point in the above example. If we only provide
two arguments then the splice operator removes everything after starting point.
Example 2: Three arguments
The third arguments specifies the length of the removed list of elements. In the above example,
we didnt specify any length thats why it removed everything after starting point. Now, lets see
what happens when we provide the third argument.
@myarray = qw(Rahul, Joe, Aject, Tim, Lisa);
@myvar = splice @array, 2, 1;
#removes only one element after Ajeet
#@myarray is qw(Rahul, Joe, Ajeet, Lisa)
# @myvar is qw(Tim)
Example 3: Fourth argument
The fourth argument is another list or an array which we are going to insert into our array.
@myarray = qw(Rahul, Joe, Ajeet, Tim, Lisa); @myvar = splice @array, 2, 1, qw(Harsh,
Alisha);
#removes only one element after Ajeet
#inserts the provided list at the same position
# @myarray is qw(Rahul, Joe, Ajeet, Harsh, Alisha, Lisa)
# @myvar is qw(Tim)
Example 4: What if we do not want to remove anything, just addition
If you do not want to remove anything, you just want to add some elements into the middle of
an array then you can specify length as 0.
@myarray = qw(Rahul, Joe, Ajeet, Tim, Lisa); @myvar = splice @array, 2, 0, qw(Harsh,
Alisha);
# removes nothing
# inserts the provided list at the starting point
#@myarray is qw(Rahul, Joe, Ajeet, Harsh, Alisha, Tim, Lisa)
#@myvar is qw()
The reverse Operator
The reverse operator takes an array of elements (or list) as input and returns it in reverse order.
For example:
@myarray = 10..15; # same as (10, 11, 12, 13, 14, 15) @myarray2 = reverse @myarray; #
@myarray2 has (15, 14, 13, 12, 11, 10)
@myarray3 = reverse 5..9; # @myarray3 has (9, 8, 7, 6, 5)
suppose you want to reverse the elements of an array and store it into the same array:
@myarray = 10..15;
@myarray = reverse @myarray;
Note: If you simply write the following statement then it wont work.
reverse @myarray;
Perl String
Strings are an essential part of the Perl language. They are scalar variables, so they start with
($) sign. A string can be defined within a single quote (') or double quote (").
Perl String
Strings are an essential part of the Perl language. They are scalar variables, so they start with
($) sign. A string can be defined within a single quote (') or double quote (").
Perl String Operators
The operators make it easy to manipulate a string in different ways. There are two types of
string operators:
Concatenation (.)
Repetition (x)
Perl Concatenation Operator
Perl strings are concatenated with a (.) sign instead of (+) sign.
1. $firstName = "Christian";
2. $lastName = "Grey";
3. $fullName = $firstName. $lastName:
4. print "$fullName\n";
Output:
Christian Grey
Perl Repeitition Operator
Perl strings can be repeated a number of times with (x) variable.
1. $text = "Thank You";
2. $output = Stext x 3;
3. print "$output\n";
Output:
Thank You Thank You Thank You
Perl Initializing and Declaring a String
In Perl. to declar
3. print "$output\n";
Output:
Thank You Thank You Thank You
Perl Initializing and Declaring a String
In Perl, to declare a string use my keyword before variable name.
A string can be initialised and declared with the following syntax:
1. my $variableName = "";
In this example, we have shown how to initialize and declare a string. We have printed several
strings together by the following ways:
Join strings using a dot (.) operator.
Supply strings as separate arguments.
Embed strings in a bigger string.
We have shown all the three methods to print the output.
# Declaring and initializing a string.
1. my $msg1 = "Welcome at JavaTpoint.";
2. my $msg2 = "This is our Perl Tutorial";
3. #printing using. operator.
4. print Smsg1. "".$msg2. "\n"; 5. #print as separate arguments.
6. print $msg1, "".$msg2, "\n";
7. #embedd string in a bigger string.
8. print "$msg1$msg2\n";
Output:
Welcome at JavaTpoint. This is our Perl Tutorial.
Welcome at JavaTpoint. This is our Perl Tutorial.
Welcome at JavaTpoint. This is our Perl Tutorial.
Perl Formatting Characters in string
Character Description
\a Bell
\b Gives a backspace
Strings can be placed within a single quote (') or double quote (") but they have little
different behavior.
1. my $user = 'Ana';
2. print 'Hello $user, welcome at our site.\n';
3. print "\n";
4. my $user = 'Ana';
5. my $day = "today";
6. print "Hello $user, welcome at our site $day.\n";
Output:
Double quote provides interpolation. Means other variables present inside the string
will represent their values. Escape characters will be replaced by their values like '\n'
will display a new line.
1. use strict;
2. use warnings;
3. # Original string
4. my $originalstring = "Our site javaTpoint provides all type of tutorials";
5. print "$originalstring\n";
6. # Offset of 4
7. my $offset = substr($originalstring, 4);
8. print "$offset\n";
9. # Offset of 4, length 15
10. my $offsetlength = substr($originalstring, 4, 15);
11. print "$offsetlength\n";
12. # Replacing length with the new string
13. my $replacing = substr($originalstring, 4, 15, "one and only site");
14. print "$originalstring\n";
Output:
M If string has a new line character, the $ and ^ will match against a new line
boundary instead of string boundary
The matching operator =~ is used to match a word in the given string. It is case sensitive, means
if string has a lowercase letter and you are searching for an uppercase letter then it will not
match.
Output:
Matching
Not Matching
It is the opposite of the earlier one (=~). If the letters match it gives the output as not matched
and vice versa.
Output:
Not Matching
Matching
1. $_ = "This is javaTpoint.";
2. if (/java/) {
3. print "Matching\n";
4. }
5. else {
6. print "Not Matching\n";
7. }
8. if (/Java/) {
9. print "Matching\n";
10. }
11. else {
12. print "Not Matching\n";
13. }
Output:
Matching
Not Matching
The matching operator m is also used to match a word in the given string.
Output:
Matching
Not Matching
The $1, $2 will print the word according to the specified bracket.
1. my $word = "CuNaHg";
2. $word =~ /(((Cu)(Na))(Hg))/;
3. print "1: $1 2: $2 3: $3 4: $4 5: $5 6: $6\n";
Output:
1: CuNaHg 2: CuNa 3: Cu 4: Na 5: Hg 6:
Perl Matching Operator with ?
It prints the matched character inside the bracket from a given string.
1. my $word = "CuNaHg";
2. $word =~ /(?:(Cu)NaHg)/;
3. print "$1\n"; # prints "Cu"
4. $word =~ /(?:Cu(Na)Hg)/;
5. print "$1\n"; # prints "Na"
6. $word =~ /(?:CuNa(Hg))/;
7. print "$1\n"; # prints "Hg?
Output:
Cu
Na
Hg
The substitution operator is just an extension of the matched operator. It allows the
replacement of text matched with some new text.
1. s/oldPattern/newPattern /;
Here we are replacing liquid with solid in the first part with s///.
In the second part, 'liquid' is replaced with 'solid' globally with s///g.
Output:
solid will remain liquid until it is evaporated
solid will remain solid until it is evaporated
Translation operator is similar as substitution operator. But translation does not use regular
expression for search on replacement values.
1. tr/oldLetter/newLetter /;
2.
Perl Translation Operator replacing one letter
Here, all the 'l' letters will be replaced with 'z' letters by translation operator.
Output:
Here, all the 'l' and 'i' letters will be replaced with 'z' and 'x' letters by translation operator.
Output:
Subroutine in Perl
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.
Perl uses the terms subroutine, method and function interchangeably.
sub subroutine_name {
body of the subroutine
}
In versions of Perl before 5.0, the syntax for calling subroutines was slightly different as
shown below. This still works in the newest versions of Perl, but it is not recommended
since it bypasses the subroutine prototypes.
Let's have a look into the following example, which defines a simple function and then call
it. Because Perl compiles your program before executing it, it doesn't matter where you
declare your subroutine.
#!/usr/bin/perl
# Function definition
sub Hello {
print "Hello, World!\n";
}
# Function call
Hello();
Hello, World!
Passing Arguments to a Subroutine
You can pass various arguments to a subroutine like you do in any other programming
language and they can be acessed inside the function using the special array @_. Thus the
first argument to the function is in $_[0], the second is in $_[1], and so on.
You can pass arrays and hashes as arguments like any scalar but passing more than one
array or hash normally causes them to lose their separate identities. So we will use
references ( explained in the next chapter ) to pass any array or hash.
Let's try the following example, which takes a list of numbers and then prints their average
−
#!/usr/bin/perl
# Function definition
sub Average {
# get total number of arguments passed.
$n = scalar(@_);
$sum = 0;
# Function call
Average(10, 20, 30);
Because the @_ variable is an array, it can be used to supply lists to a subroutine. However,
because of the way in which Perl accepts and parses lists and arrays, it can be difficult to
extract the individual elements from @_. If you have to pass a list along with other scalar
arguments, then make list as the last argument as shown below −
#!/usr/bin/perl
# Function definition
sub PrintList {
my @list = @_;
print "Given list is @list\n";
}
$a = 10;
@b = (1, 2, 3, 4);
Given list is 10 1 2 3 4
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. For example −
#!/usr/bin/perl
# Function definition
sub PrintHash {
my (%hash) = @_;
name : Tom
age : 19
Returning Value from a Subroutine
You can return a value from subroutine like you do in any other programming language. If
you are not returning a value from a subroutine then whatever calculation is last performed
in a subroutine is automatically also the return value.
You can return arrays and hashes from the subroutine like any scalar but returning more
than one array or hash normally causes them to lose their separate identities. So we will use
references ( explained in the next chapter ) to return any array or hash from a function.
Let's try the following example, which takes a list of numbers and then returns their average
−
#!/usr/bin/perl
# Function definition
sub Average {
# get total number of arguments passed.
$n = scalar(@_);
$sum = 0;
return $average;
}
# Function call
$num = Average(10, 20, 30);
print "Average for the given numbers : $num\n";
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. A 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.
Following is an example showing you how to define a single or multiple private variables
using my operator −
sub somefunc {
my $variable; # $variable is invisible outside somefunc()
my ($another, @an_array, %a_hash); # declaring many variables at once
}
Let's check the following example to distinguish between global and private variables −
#!/usr/bin/perl
# Global variable
$string = "Hello, World!";
# Function definition
sub PrintHello {
# Private variable for PrintHello function
my $string;
$string = "Hello, Perl!";
print "Inside the function $string\n";
}
# Function call
PrintHello();
print "Outside the function $string\n";
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. Lexical scoping is done with my, which works more
like C's auto declarations.
If more than one variable or expression is given to local, they must be placed in parentheses.
This operator works by saving the current values of those variables in its argument list on
a hidden stack and restoring them upon exiting the block, subroutine, or eval.
Let's check the following example to distinguish between global and local variables −
#!/usr/bin/perl
# Global variable
$string = "Hello, World!";
sub PrintHello {
# Private variable for PrintHello function
local $string;
$string = "Hello, Perl!";
PrintMe();
print "Inside the function PrintHello $string\n";
}
sub PrintMe {
print "Inside the function PrintMe $string\n";
}
# Function call
PrintHello();
print "Outside the function $string\n";
There are another type of lexical variables, which are similar to private variables but they
maintain their state and they do not get reinitialized upon multiple calls of the subroutines.
These variables are defined using the state operator and available starting from Perl 5.9.4.
Let's check the following example to demonstrate the use of state variables −
#!/usr/bin/perl
sub PrintCount {
state $count = 0; # initial value
for (1..5) {
PrintCount();
}
Value of counter is 0
Value of counter is 1
Value of counter is 2
Value of counter is 3
Value of counter is 4
#!/usr/bin/perl
{
my $count = 0; # initial value
sub PrintCount {
print "Value of counter is $count\n";
$count++;
}
}
for (1..5) {
PrintCount();
}
Subroutine Call Context
The context of a subroutine or statement is defined as the type of return value that is
expected. This allows you to use a single function that returns different values based on
what the user is expecting to receive. For example, the following localtime() returns a string
when it is called in scalar context, but it returns a list when it is called in list context.
In this example, the value of $timestr is now a string made up of the current date and time,
for example, Thu Nov 30 15:21:33 2000. Conversely −
Now the individual variables contain the corresponding values returned by localtime()
subroutine.