Unit 3
Unit 3
• Syllabus
• Introduction to PERL and Scripting
– Scripts and Programs, Origin of Scripting, Scripting Today,
Characteristics of Scripting Languages, Uses for Scripting
Languages, Web Scripting, and the universe of Scripting
Languages.
– PERL- Names and Values, Variables, Scalar Expressions,
Control Structures, arrays, list, hashes, strings, pattern and
regular expressions, subroutines.
1
Script and Program
• A Script is a set of instructions that are interpreted.
Scripts are written using a different kind of language
called scripting languages like python, perl, ruby, shell
script, VB Script, etc.
2
Script and Program
Programming Languages Scripting Languages
5
Characteristics of Scripting Languages
– Both batch and interactive use
– Economy of expression
– Lack of declarations, simple scoping rules
– Flexible dynamic typing
– Easy access to other programs
6
Uses for Scripting Languages
– Scripting languages are of two kinds
• Traditional Scripting
• Modern Scripting
– Traditional Scripting
• The activities which require traditional scripting include
– System administration
– Controlling Remote Applications
– System and Application extensions
– Experimental Programming
– Command Line interface
– Modern Scripting
• Visual Scripting
• Scriptable components
• Client side and Server side scripting
7
Web Scripting
• Web script, a computer programming language for adding dynamic
capabilities to world wide web pages.
• Web scripting can be add information to a page as a reader uses it or
let the reader enter information that may be passed on to the order
department of an online business.
• Processing web forms
• Creating Dynamic web pages with enhanced visual effects and user
interaction.
• Dynamically Generating web pages “on the fly” from material held in a
database.
8
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.
• The Perl interpreter can be embedded into other systems such as web servers
and database servers.
11
Names and Values
• The data can be either number, characters, or more complex such as a list.
• Data is held as value. The following examples are values:
10
20.2
"Perl syntax"
• To hold a piece of data, you need variables. You use a variable to store a
value. And through the name of the variable, you can process the value.
• The following illustrates some variables in Perl:
12
Expressions
In Perl, an expression is anything that returns a value.
• The expression can be used in a larger expression or a statement.
• The expression can be a literal number, complex expression with operators,
or a function call.
• For example, 3 is an expression that returns a value of 3. The $a + $b is an
expression that returns the sum of two variables: $a and $b.
13
Statements
14
Blocks
15
Whitespace
16
Keywords
17
Variables
18
Variables
Scalar Variable
$name = "Anastasia";
$rank = "9th";
$marks = 756.5;
Print “$name”
Print “$rank”
Print “$marks”
Scalar Operations
my $x = 5;
say $x;
my $y = 3;
say $y;
say $x + $y;
say $x . $y;
say $x x $y;
19
Variables-Scalar (single)-Expressions
20
Variables-An Array
• 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 −
@ages = (25, 30, 40);
@names = ("John Paul", "Lisa", "Kumar");
print "\$ages[0] = $ages[0]\n";
print "\$ages[1] = $ages[1]\n";
print "\$ages[2] = $ages[2]\n";
print "\$names[0] = $names[0]\n";
print "\$names[1] = $names[1]\n";
print "\$names[2] = $names[2]\n“
OUTPUT:
$ages[0] = 25
$ages[1] = 30
$ages[2] = 40
$names[0] = John Paul
$names[1] = Lisa
21
$names[2] = Kumar
Variables-Hashes
• A Perl hash is defined by key-value pairs.
• Perl stores elements of a hash in such an optimal way that you
can look up its values based on keys very fast.
• Example
22
Variables-Subroutine
• A Perl subroutine or function is a group of statements that together
performs a task. You can divide up your code into separate subroutines.
• 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 );
EXAMPLE
sub Hello {
print "Hello, World!\n"; }
Hello(); # Function call
When above program is executed, it produces the following result −
Hello, World!
23
Control Structures
• If-else
• if-elsif-else
• while/until
• for/foreach
24
Control Structures
If-else
Syntax
Example:
25
Control Structures
if-elsif-else.
Syntax
26
Control Structures
if-elsif-else
Example:
27
Control Structures
for:
Syntax
for (init statement; condition; increment/decrement )
{
# Code to be Executed
}
Example:
# Perl program to illustrate the for loop
for ($count = 1 ; $count <= 3 ; $count++)
{
print “$count”
}
28
Control Structures
foreach variable
{
# Code to be Executed
}
Example:
# Array
@data = (‘for', ‘each', ‘example');
# foreach loop
foreach $word (@data)
{
print $word
}
29
Control Structures
OUTPUT:
10 11 12 13 14 15 16 17 18 19 20
30
Control Structures
until (condition)
{
# Statements to be executed
}
Example:
# until loop
a=10
until ($a < 1)
{
print "$a ";
$a = $a - 1;
OUTPUT:
10 9 8 7 6 5 4 3 2 1 31
}
Perl Strings
• In perl, a string is a sequence of characters surrounded by some kinds of
quotation marks.
• Ex: $str1=“string with double quotes”;
$str2=‘string with single quote”;
• Note: Double quoted string replaces variables inside it by their values, while
the single quoted strings treats them as text.
• The operator make it easy to manipulate a string in different ways. There
are two types of string operators. They are
– Concatenation (.)
– Repetition(X)
• Example
• Print “this” .”is” .”perl strings”; # output: this is perl strings
• Print “hello”X4 # prints hellohellohellohello
32
Perl Strings functions
• length(string);
• uc(string);
• lc(string);
• Index(string, substring);
• Substr(string, starting_position,ending_position)
33
Perl Strings functions
34
Perl Strings functions
Example
my $s=“Learning perl is easy”
my $sub=“perl”;
my $p=index($s, $sub);
Print(qw\The substring “$sub” found at position “$p” in string “$s”\,
“\n”);
OUTPUT:
The substring perl found at position 9 in string Learning perl is eary.
35
Perl Strings functions
36
Perl List
37
Simple Perl List
38
Complex Perl List
39
Perl List –Accessing
• Syntax: $listname[index];
40
Perl List –using qw function
41
Perl List –using Flattening List
42
Perl List –slicing List
@list1=(1, “hello”,3, “for”,5);
@list2=@list1[1,2,4]; #slice positions
Print “sliced list: @list2;
OUTPUT:
Hello 3 5
43
Perl Arrays
• A Perl array variable stores an ordered list of scalar values.
• To refer a single element of Perl array, variable name will be preceded with
dollar ($) sign followed by index of element in the square bracket.
• Syntax
@arrayName = (element1, element2, element3..);
#!/usr/bin/perl
@num = (2015, 2016, 2017);
@string = ("One", "Two", "Three");
print "$num[0]\n";
print "$num[1]\n";
print "$num[2]\n";
print "$string[0]\n";
print "$string[1]\n";
print "$string[2]\n";
Print “@num”;
44
Perl Array accessing
• To access a single element of a Perl array, use ($) sign before
variable name.
• You can assume that $ sign represents singular value and @ sign
represents plural values.
• Variable name will be followed by square brackets with index
number inside it.
• Indexing will start with 0 from left side and with -1 from right
side.
@months = qw/
Jan Feb Mar Apr May Jun Jul Aug Sept Oct Nov Dec/;print "$months[0]\
n";
print "$months[1]\n";
print "$months[7]\n";
print "$months[9]\n";
print "$months[6]\n";
45
print "$months[-3]\n";
Perl Array accessing
46
Perl Array Functions
47
Push on Array
48
Pop on Array
49
Shift on Array
50
Unshift on Array
51
splice on Array
52
sorting on Array
53
Merging TWO arrays
54
Splitting arrays
55
Join Arrays
56
Perl Hashes
• The hashes is the most essential and influential part of the perl
language.
• A hash is a group of key-value pairs.
• The keys are unique strings and values are scalar values. Hashes
are declared using my keyword.
• Hashes are same like as arrays, but hashes are unordered and
also the hash elements are accessed using its value while array
elements are accessed using its index value.
• Syntax
my %hashName = ( "key" => "value”);
57
Perl Hash Accessing
• To access single element of hash, ($) sign is used before the variable name
and then key element is written inside {} braces.
Example:
my %capitals = ( "India" => "New Delhi", "South Korea" => "Seoul", "USA" => "Wa
shington, D.C.", "Australia" => "Canberra" );
print " $capitals{'India'}\n";
print "$capitals{'South Korea'}\n";
print "$capitals{'USA'}\n";
print "$capitals{'Australia'}\n";
OUTPUT:
New Delhi
Seoul
Washington,
D.C. Canberra
58
Perl Hash Accessing
• To access single element of hash, ($) sign is used before the variable name. And
then key element is written inside {} braces.
my %capitals = (
"India" => "New Delhi",
"South Korea" => "Seoul",
"USA" => "Washington, D.C.",
"Australia" => "Canberra"
);
print"$capitals{'India'}\n";
print"$capitals{'South Korea'}\n";
print"$capitals{'USA'}\n";
print"$capitals{'Australia'}\n";
OUTPUT:
New Delhi
Seoul
Washington,
D.C. Canberra
59
Perl sorting Hash by key using foreach
• You can sort a hash using either its key element or value element. Perl provides a
sort() function for this. In this example, we'll sort the hash by its key elements.
my %capitals = (
"India" => "New Delhi",
"South Korea" => "Seoul",
"USA" => "Washington, D.C.",
"Australia" => "Canberra"
);
# Foreach loop
foreach $key (sort keys %capitals) {
print "$key: $capitals{$key}\n";
}
60
Perl Removing Hash Elements
• To remove a hash element, use delete() function.
• Here, we have removed both the key-value pairs which were added in the
last example.
my %capitals = (
"India" => "New Delhi",
"South Korea" => "Seoul",
"USA" => "Washington, D.C.",
"Australia" => "Canberra"
"Germany " => " Berlin"
" UK " => "London"
);
while (($key, $value) = each(%capitals)){
print $key.", ".$value."\n"; }
#removing element
delete($capitals{Germany});
delete($capitals{UK});
# Printing new hash
print "\n";
while (($key, $value) = each(%capitals)){
print $key.", ".$value."\n"; }
61
Patterns and Regular Expressions
• A pattern is a sequence of characters to be searched for in a character
string.
– In perl, patterns are normally enclosed in slash character : ex. /def/
– This pattern represents the pattern def
– Example:
$string= “welcome to perl script”;
If ($sring=~/perl/)
Print “ found”; else print “not found”;
62
Patterns and Regular Expressions
63
Regular Expressions
• A regular expression is a string of characters
that defines the pattern or patterns you are
viewing
• A RE is also referred as regex or regexp
• A regular expression can be either simple or
complex, depending on the pattern you want
to match
• Syntax: string =~regx;
64
Complex Regular Expressions: Meta characters
65
Subroutines
• A perl function or subroutine is a group of statements that
together perform a specific task.
• The word subroutines is used most in perl programming
because it created using “sub”
• Syntax
Sub subroutine_name
{
#body of the function or subroutine
}
• In perl scripting, subroutines can be called by passing the
parameters list to it as follows
• Subrountine_name(parameters_list);
66
Subroutines
• Example
sub add(a,b);
{
return (a+b);
}
$sum=add(4,6);
Print “$sum”;
67
Subroutines
• Advantages
– It helps to reuse the code
– Organizing the code in structural format
– It increases code readability
68