EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
Â
Perl Reference.ppt
1. UNIT I â Perl Basics
Lecture 1- Introduction to Perl
Programming
2. Introduction
Perl is a family of high-level, general-purpose, interpreted, dynamic
programming languages.
The languages in this family include Perl 5 and Perl 6.
Though Perl is not officially an acronym, there are various backronyms in use,
the most well-known being "Practical Extraction and Reporting Language".
Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix
scripting language to make report processing easier. Since then, it has
undergone many changes and revisions.
Lecture 1 â Topic Name
2
5. The Perl languages borrow features from other programming languages
including C, shell script (sh), AWK, and sed. They provide powerful text
processing facilities without the arbitrary data-length limits of many
contemporary Unix command line tools, facilitating easy manipulation of text
files.
Perl 5 gained widespread popularity in the late 1990s as a CGI scripting
language, in part due to its unsurpassed regular expression and string parsing
abilities
Introduction
5
6. A scripting or script language is a programming language that supports
scripts, programs written for a special run-time environment that automate the
execution of tasks that could alternatively be executed one-by-one by a human
operator. Scripting languages are often interpreted (rather than compiled).
Primitives are usually the elementary tasks or API calls, and the language
allows them to be combined into more complex programs. Environments that
can be automated through scripting include software applications, web pages
within a web browser, the shells of operating systems (OS), embedded
systems, as well as numerous games. A scripting language can be viewed as a
domain-specific language for a particular environment; in the case of scripting
an application, this is also known as an extension language.
Scripting languages
6
7. In an interpreted environment, the instructions are executed immediately after
parsing. Both tasks are performed by the interpreter. Interpreted languages
include the MS-Dos Batch language (the OS itself is the interpreter), shell
scripts in Unix/Linux systems, Java, Perl and BASICA (a very old BASIC
language). Advantages of interpreted languages include relative ease of
programming (since once you type your instructions into a text file, the
interpreter can run it) and no linker is required. Disadvantages include poor
speed performance and that you do not generate an executable (and therefore
distributable) program. The interpreter must be present on a system to run the
program.
Interpreted vs. Compiled Languages
7
8. Compilers parse the instructions into machine code and store them in a
separate file for later execution. Many modern compilers can compile (parse)
and execute in memory, giving the 'appearance' of an interpreted language.
However, the key difference is that parsing and execution occurs in two distinct
steps. Examples include newer forms of BASIC (such as Visual Basic), C/C++,
Delphi and many others. In a compiled environment, you may speak of several
separate files: source code (the text instructions you actually enter), object
code (the parsed source code) and the executable (the linked object code).
There is definitely an increase in complexity in using compilers, but the key
advantages are speed performance and that you can distribute stand-alone
executables.
Interpreted vs. Compiled Languages
8
13. ī§Perl takes the best features from other languages, such as C, awk, sed, sh,
and BASIC, among others.
ī§Perl is an interpreted language, which means that your code can be run as is,
without a compilation stage that creates a non portable executable program
ī§Perls database integration interface DBI supports third-party databases
including Oracle, Sybase, Postgres, MySQL and others.
ī§Perl works with HTML, XML, and other mark-up languages.
ī§Perl works cross platform.
ī§Perl supports both procedural and object-oriented programming.
ī§Perl interfaces with external C/C++ libraries through XS or SWIG.
ī§Perl is extensible. There are over 20,000 third party modules available from
the Comprehensive Perl Archive Network (CPAN).
ī§The Perl interpreter can be embedded into other systems.
Perl Features
13
14. ī§Perl used to be the most popular web programming language due to its text
manipulation capabilities and rapid development cycle.
ī§Perl is widely known as " the duct-tape of the Internet".
ī§Perl can handle encrypted Web data, including e-commerce transactions.
ī§Perl can be embedded into web servers to speed up processing by as much
as 2000%.
ī§Perl's mod_perl allows the Apache web server to embed a Perl interpreter.
ī§Perl's DBI package makes web-database integration easy.
Perl and the Web
14
27. Unit No: 1 Unit name: Perl Basics
Lecture 3:
Datatypes and Variables
28. 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.
Data Types in Perl
Lecture 3:
Datatypes and Variables
28
32. ī§ 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 maintains every variable type in a separate namespace. So you can,
without fear of conflict, use the same name for a scalar variable, an array, or
a hash. This means that $foo and @foo are two different variables.
Perl - Variables
Lecture 3:
Datatypes and Variables
32
34. 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. Simply saying it could be
anything, but only a single thing.
Scalar Variables
Lecture 3:
Datatypes and Variables
34
35. 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 Variables
Lecture 3:
Datatypes and Variables
35
36. 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.
Hash Variables
Lecture 3:
Datatypes and Variables
36
37. The strict pragma checks for unsafe programming constructs. Strict forces a
programmer to declare all variables as package or lexically scoped variables.
Strict also forces specific syntax with sub, forcing the programmer to call each
subroutine explicitly. The programmer also needs to use quotes around all
strings, and to call each subroutine explicitly, which forces a distrust of bare
words.
The warnings pragma sends warnings when the Perl compiler detects a
possible typographical error and looks for potential problems. There are a
number of possible, but warnings mainly look for the most common syntax
mistakes and common scripting bugs.
Perl: Strict and Warnings
Lecture 3:
Datatypes and Variables
37
38. ī§ Variable names can start with a letter, a number, or an underscore, although
they normally begin with a letter and can then be composed of any
combination of letters, numbers, and the underscore character.
ī§ Variables can start with a number, but they must be entirely composed of
that number; for example, $123 is valid, but $1var is not.
ī§ Variable names that start with anything other than a letter, digit, or
underscore are generally reserved for special use by Perl
ī§ Variable names are case sensitive; $foo, $FOO, and $fOo are all separate
variables as far as Perl is concerned.
ī§ As an unwritten (and therefore unenforced) rule, names all in uppercase are
constants.
ī§ All scalar values start with $, including those accessed from an array of
hash, for example $array[0] or $hash{key}.
ī§ Namespaces are separate for each variable typeâthe variables $var, @var,
and %var are all different variables in their own right. Limited to 255
characters.
Basic Naming Rules in Perl
Lecture 3:
Datatypes and Variables
38
40. Unit No: 1 Unit name: Perl Basics
Lecture 4:
Perl Operators
41. ī§ Input refers to getting information into your program
ī§ Output refers to getting information out of your program
I/O is how computer programs talk to the rest of the âworldâ
Perl provides access to the standard files: STDIN,STDOUT, STDERR
STDIN is accessed through the angle brackets (<>) operator. When placed in a
scalar context, the operator returns the next line; when place in an array
context, it returns the entire file, one line per item in the array.
Perl Basic Input Output
Lecture 4:
Perl Operators
41
42. One of these is for input to your program, and two are for output from your program
Input
â By default, Perl has a connection set up for taking information entered from the
keyboard.
This connection is referred to as
STDIN
Output
â 1) By default, Perl has a connection set up for writing data out to your terminal
(screen).
This connection is referred to as
STDOUT
2) By default, Perl has a connection set up for writing diagnostic messages,
(warnings, etc.) to your terminal
. This connection is referred to as
STDERR
You can change the default locations for STDIN,STDOUT and STDERR
Every Perl script starts with three connections to
the outside world
Lecture 4:
Perl Operators
42
43. print âPlease enter your name: â;
$name = <STDIN>;
print âHello $name. Glad to meet you.â;
Reading data from STDIN
Lecture 4:
Perl Operators
43
46. Simple answer can be given using the expression 4 + 5 is equal to 9. Here 4
and 5 are called operands and + is called operator. Perl language supports
many operator types, but following is a list of important and most frequently
used operators â
ī§ Arithmetic Operators
ī§ Equality Operators
ī§ Logical Operators
ī§ Assignment Operators
ī§ Bitwise Operators
ī§ Logical Operators
ī§ Quote-like Operators
ī§ Miscellaneous Operators
Perl - Operators
Lecture 4:
Perl Operators
46
51. There are following logical operators supported by Perl language. Assume
variable $a holds true and variable $b holds false then â
Perl Logical Operators
Lecture 4:
Perl Operators
51
53. Unit No: 1 Unit name: Perl Basics
Lecture 5:
Loops and Controls
54. 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.
Perl Conditional Statements
Lecture 5:
Loops and Controls
54
57. 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.
When using if , elsif , else statements there are few points to keep in mind.
ī§ An if can have zero or one else's and it must come after any elsif's.
ī§ An if can have zero to many elsif's and they must come before the else.
ī§ Once an elsif succeeds, none of the remaining elsif's or else's will be tested.
Perl IF...ELSIF statement
Lecture 5:
Loops and Controls
57
76. Loop control statements change the execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope
are destroyed.
Loop Control Statements
Lecture 5:
Loops and Controls
76
77. The Perl next statement starts the next iteration of the loop. You can provide a
LABEL with next statement where LABEL is the label for a loop. A next
statement can be used inside a nested loop where it will be applicable to the
nearest loop if a LABEL is not specified.
next
Lecture 5:
Loops and Controls
77
79. A continue BLOCK, is always executed just before the conditional is about to
be evaluated again. A continue statement can be used with while and foreach
loops. A continue statement can also be used alone along with a BLOCK of
code in which case it will be assumed as a flow control statement rather than a
function.
continue
Lecture 5:
Loops and Controls
79
82. Unit No: 1 Unit name: Perl Basics
Lecture 6:
Printing Functions
83. The printf operator takes a format string followed by a list of things to print
Printing Formats: printf - string formatting:
Lecture 6:
Printing Functions
83
88. This function uses FORMAT to return a formatted string based on the values in
LIST. Essentially identical to printf, but the formatted string is returned instead
of being printed.
Perl sprintf Function
Lecture 6:
Printing Functions
88
90. Unit No: 1 Unit name: Perl Basics
Lecture 7:
Perl Arrays
91. Arrays are a special type of variable that store list style data types. Each object
of the list is termed an element and elements can either be a string, a number,
or any type of scalar data including another variable.
Array Variables
Lecture 7:
Perl Arrays
91
92. Arrays are stored in array variables. An array variable starts with @ sign
ī§ Names can be upto 255 characters long and can contain numbers, letters
and underscores.
ī§ Names are case sensitive.
ī§ Array variables names can start with a number and then can only contain
numbers.
ī§ Scalar and array variable names do not conflict with each other. The variable
$x is different from @x.
Rules for naming array variables
Lecture 7:
Perl Arrays
92
94. Each element of the array can be indexed using a scalar version of the same
array. When an array is defined, PERL automatically numbers each element in
the array beginning with zero. This phenomenon is termed array indexing.
PERL - Array Indexing
Lecture 7:
Perl Arrays
94
95. Elements can also be indexed backwards using negative integers instead of
positive numbers.
Lecture 7:
Perl Arrays
95
96. Quotations can be a hassle, especially if the array you wish to build has more
than 5 elements. Use this neat little subroutine (quote word operator) to remove
the need for quotes around each element when you define an array.
PERL - The qw Subroutine
Lecture 7:
Perl Arrays
96
97. PERL offers a shortcut for sequential numbers and letters. Rather than typing
out each element when counting to 100 for example, we can do something like
this:
PERL - Sequential Number Arrays
Lecture 7:
Perl Arrays
97
101. ī§ scalar - find the length of the array
ī§ $# - gives the index no of last element of the array
ī§ defined - checks whether value of that index is defined or not
ī§ undef - undefines the value of particular index
ī§ delete - deletes an element from the array
ī§ pop - returns the last element of array and reduces its length by 1
ī§ push - adds incoming element in the end of the array
ī§ shift - returns the first element of array and reduces its length by 1
ī§ unshift - adds incoming element in the start of the array
ī§ splice - inserts or replaces an element at an arbitrary position in an array
ī§ split - transform a string into an array, splits string expr at occurrences of
pattern
ī§ join - transform an array into a string. Joins the list elements in single string
separated by pattern
ī§ reverse â reverses elements in the array
ī§ sort - sorts the elements of the array
Array Functions
Lecture 7:
Perl Arrays
101
105. Basically, the expression $a <=> $b (or $a cmp $b for strings) returns one of the
values 1, 0, -1 if $a is, respectively, larger, equal or lower than $b.
Lecture 7:
Perl Arrays
105
106. Create a new array with elements of another array
Lecture 7:
Perl Arrays
106
113. This function returns the position of the first occurrence of SUBSTR in STR,
starting at the beginning (starting at zero), or from POSITION if specified.
Perl index Function
Lecture 8:
String Functions
113
116. This function operates similar to index, except it returns the position of the last
occurrence of SUBSTR in STR. If POSITION is specified, returns the last
occurrence at or before that position.
Perl rindex Function
Lecture 8:
String Functions
116
119. This function returns a substring of EXPR, starting at OFFSET within the string. If
OFFSET is negative, starts that many characters from the end of the string. If LEN
is specified, returns that number of bytes, or all bytes up until end-of-string if not
specified. If LEN is negative, leaves that many characters off the end of the string.
If REPLACEMENT is specified, replaces the substring with the REPLACEMENT
string.
If you specify a substring that passes beyond the end of the string, it returns only
the valid element of the original string.
Perl substr Function
Lecture 8:
String Functions
119
124. Unit No: 1 Unit name: Perl Basics
Lecture 9:
File Handling
125. 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. However, when
you associate a filehandle, you can specify the mode in which the filehandle is
opened.
Perl - File I/O
Lecture 9:
File Handling
125
136. Unit No: 2 Unit name: Essential Perl
Lecture 10:
Perl Subroutines
137. The String Operators (. and x)
Lecture 10:
Perl Subroutines
137
Perl has two different string operators-the concatenation (.) operator and the
repetition (x) operator. These operators make it easy to manipulate strings in
certain ways. Let's start with the concatenation operator. Strings can be
concatenated by the . operator.
For example:
$first_name = "David";
$last_name = "Marshall";
$full_name = $first_name . " " . $last_name;
we need the " " to insert a space between the strings.
138. Lecture 10:
Perl Subroutines
138
Strings can be repeated with tt x operator
For example:
$first_name = "David";
$david_cubed = $first_name x 3;
which gives "DavidDavidDavid".
145. A function is a block of code that has a name and it has a property that it is
reusable i.e. it can be executed from as many different points in a Program as
required.
Function groups a number of program statements into a unit and gives it a
name. This unit can be invoked from other parts of a program. A computer
program cannot handle all the tasks by it self. Instead its requests other
program like entities â called functions to get its tasks done. A function is a self
contained block of statements that perform a coherent task of same kind
The name of the function is unique in a Program and is Global. It means that a
function can be accessed from any location with in a Program. We pass
information to the function called arguments specified when the function is
called. And the function either returns some value to the point it was called from
or returns nothing.
We can divide a long program into small blocks which can perform a certain
task. A function is a self contained block of statements that perform a coherent
task of same kind.
Function
Lecture 10:
Perl Subroutines
145
151. 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.
Lecture 10:
Perl Subroutines
151
152. 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.
Private Variables in a Subroutine
Lecture 10:
Perl Subroutines
152
153. Types of subroutines
Lecture 10:
Perl Subroutines
153
Function
without
parameter
without
return value
Function
without
parameter
with return
value
Function
with
parameter
with return
value
Function
with
parameter
without
return value
Types
162. Unit No: 2 Unit name: Essential Perl
Lecture 11:
Perl Regular Expressions
163. A regular expression is a string of characters that defines the pattern or
patterns you are viewing. Basically, a regular expression is a pattern describing
a certain amount of text. Their name comes from the mathematical theory on
which they are based. But we will not dig into that. You will usually find the
name abbreviated to "regex" or "regexp".
b[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,}b is a more complex pattern. It
describes a series of letters, digits, dots, underscores, percentage signs and
hyphens, followed by an at sign, followed by another series of letters, digits and
hyphens, finally followed by a single dot and two or more letters. In other
words: this pattern describes an email address. With the above regular
expression pattern, you can search through a text file to find email addresses,
or verify if a given string looks like an email address.
Regular Expressions in Perl
Lecture 11:
Perl Regular Expressions
163
164. There are three regular expression operators within Perl.
Lecture 11:
Perl Regular Expressions
164
165. The match operator, m//, is used to match a string or statement to a regular
expression.
The Match Operator
Lecture 11:
Perl Regular Expressions
165
167. Note that the entire match expression that is the expression on the left of =~ or
!~ and the match operator, returns true (in a scalar context) if the expression
matches. 1 if matches the regex, or 0 if the match fails.
Lecture 11:
Perl Regular Expressions
167
168. Regular expression variables include $, which contains whatever the last
grouping match matched; $&, which contains the entire matched string; $`,
which contains everything before the matched string; and $', which contains
everything after the matched string.
Regular Expression Variables
Lecture 11:
Perl Regular Expressions
168
170. This is the transliteration operator; it replaces all occurrences of the characters
in SEARCHLIST with the characters in REPLACEMENTLIST.
The Translation Operator (Transliterate)
Lecture 11:
Perl Regular Expressions
170