SL Notes - (3&4) Units
SL Notes - (3&4) Units
In the context of computing, both "script" and "program" refer to sequences of instructions that are
executed by a computer. However, there are some distinctions between the two:
❖ Script:
➢ A script is typically a sequence of commands or instructions written in a scripting language.
➢ It is often interpreted rather than compiled, meaning that the instructions are executed line by line
by an interpreter at runtime.
➢ Scripts are commonly used for tasks such as automating repetitive tasks, system administration,
web development (server-side scripting), and quick prototyping.
➢ Examples of scripting languages include Python, Perl, Ruby, JavaScript (when used outside of
web browsers, e.g., Node.js), and shell scripting languages like Bash.
➢ Example:
# Script to greet the user by name
name = input("What's your name? ")
print(f"Hello, {name}!")
❖ Program:
➢ A program is a sequence of instructions written in a programming language.
➢ It can be compiled into machine code or bytecode before execution.
➢ Programs can be large and complex, consisting of multiple files/modules and utilizing libraries and
frameworks.
➢ They are used for developing a wide range of applications, including desktop software, mobile
apps, web applications, games, operating systems, and more.
➢ Examples of programming languages used for writing programs include C, C++, Java, C#, Swift,
Kotlin, and many others.
Example:
// Program to calculate the area of a circle (simplified)
public class CircleArea {
public static void main(String[] args) {
double radius = 5.0;
double area = Math.PI * radius * radius;
System.out.println("Area of the circle: " + area);
}
}
Origins of scripting:
The term "script" in computing began in the early 1970s with UNIX. It started with "shell scripts," sequences of
commands stored in files and run like typing them directly. This use of "script" spread to other languages like
AWK and Perl, where scripts are text files executed directly without compilation.
Early uses of "script" mirrored other fields. DOS dial-up connections used scripts in a special language to
automate connection steps, similar to film scripts guiding actors and cameras. Apple's HyperCard, a hypertext
system, used "scripts" in its HyperTalk language to trigger actions based on user interactions (like mouse clicks) to
be user-friendly (avoiding the scary word "program"). In both these cases, scripts were about control: controlling a
modem's actions or changing how things appeared on the screen. (Script and control are often linked, but scripts
have other uses too.)
An important distinction is made: scripts become truly powerful when they go beyond simple sequences and
incorporate programming concepts like loops and branching. This is when they become more than just following
commands in order.
Scripting today:
Scripting as a way to give instructions to your computer in a simpler language. Instead of complex code, you
use something easier to understand, kind of like how recipes are easier to follow than engineering manuals.
1. Building things fast (Rapid Application Development): Think of it like using Legos. Scripting languages
let you connect pre-made building blocks (software components) to create new programs quickly. This is
useful when you need a simple program and don't have time to write everything from scratch.
2. Controlling existing programs: Scripting can be like a remote control for your software. If a program
allows you to control it with scripts, you can write scripts to automate tasks you do often. For example,
you could write a script to automatically format all your reports in a specific way.
3. Sometimes a simpler way to program: Scripting languages can sometimes be used for more general
programming tasks, especially for things like managing computers behind the scenes (system
administration). Imagine you have to do a lot of repetitive tasks on your computer, like copying files or
setting up new user accounts. Scripting languages can automate these tasks, making your work much faster.
1.Traditional scripting
1.System administration automating everyday tasks, building data reduction tools
2.Controlling applications remotely
3.System and application extensions
4.'Experimental' programming
5.Building command-line interfaces to applications based on C libraries
6.Server-side form on the Web using CGI.
Automating Everyday Tasks:
Imagine a system administrator who spends hours every week resetting passwords for forgetful users. A script can
be written to automate this process. The script would connect to the user database, verify the request, and reset the
password according to predefined rules. This frees up the administrator's time for more complex tasks.
Building Data Reduction Tools:
Think of a company that receives daily sales data from hundreds of stores. A script can be written to analyze this
data, calculating total sales, identifying top-selling items, and highlighting any unusual trends. This summarized
information is much easier to understand than looking at raw data from hundreds of sources.
Controlling Remotely:
Imagine having multiple servers in different locations. A script can be written to check the status of these servers
remotely, ensuring they are running smoothly. If a server goes down, the script can even send an alert or attempt to
restart it automatically.
System and Extension Examples:
❖ Adding a custom menu to an existing program: A script could be used to create a menu within a
complex software program, providing users with quick access to frequently used functions.
❖ Extending a web browser's functionality: A script could be written to add features to a web browser, like
automatically blocking certain types of ads or translating web pages on the fly.
Experimental Programming:
Scripting languages are often used as a "scratchpad" for programmers. They can quickly write and test new code
ideas or algorithms in a scripting language before investing time in a more complex language for a larger project.
It's like trying out a recipe with readily available ingredients before committing to a complex meal.
Command-Line Interfaces (CLIs):
While most users interact with computers through a mouse and graphical interfaces, scripting languages can be
used to create text-based interfaces. These can be simpler to develop and can be useful for automating tasks or for
experienced users who prefer keyboard shortcuts.
Server-Side Scripting (CGI):
When you fill out a form on a website, for example, a contact form or a search bar, the information you submit
needs to be processed somehow. In the early days of the web, scripting languages like CGI were commonly used
on web servers to handle this processing. The script would receive the submitted data, perform any necessary
actions (like storing it in a database or sending an email), and potentially generate a response to be displayed on
the webpage.
While CGI is less common today, it provides a good historical example of how scripting languages were used in
web development. Modern web development often uses different scripting languages and frameworks for handling
form submissions and other web interactions.
Traditional Scripting Languages (Open Source):
❖ Open Source languages are a cornerstone of traditional scripting. Their code is freely available for anyone
to see, use, and modify. This allows for a collaborative development process where programmers can
contribute improvements and share best practices.
❖ Perl and TCL are two prominent examples of traditional scripting languages. They were among the first
languages to be widely adopted for scripting tasks, especially in system administration. While other
languages like Python have become more popular in recent years, Perl and TCL are still used in some
environments.
2.Modern scripting
1. Visual scripting.
2. Using scriptable components - macros for desktop applications and compound documents
3. Client-side and server-side Web scripting.
Visual scripting:
Visual scripting is the process of constructing a graphical interface from a collection of
visual objects ('controls' in Microsoft 'widgets' in Tcl/Tk and Perl-Tk), which have properties (attributes),
e.g. foreground and background colours , text on a button etc. that can be set by a program written in an
appropriate language Some objects(e.g button) respond to external events such as mouse clicks and the
response to each action is defined by a script.
Scriptable components:
● They are software components designed to be controlled by scripting languages.
● This means they expose an "interface," which is like a set of instructions on how to interact with them
using a scripting language.
● Visual components: Buttons, menus, and other interactive elements in applications like Visual Basic can be
scripted to change behavior (e.g., changing button text based on user actions).
● Embedded objects: Imagine a chart in a word processing document. Scripting could be used to update the
chart data dynamically.
● Component objects: These are larger functionalities within an application. Examples include spell
checkers, database connections, or internet access functions. Scripting can be used to customize their
behavior.
● Model elements: Think of a website. Scripting languages can manipulate elements on the page to create
dynamic interactions.
● Scriptable objects make software development more efficient and flexible. Developers can reuse
components and customize their behavior using scripts instead of writing everything from scratch.
● This approach is becoming increasingly important in modern software due to its modularity and ease of
customization
The Component Object Model (COM) is a software development standard created by Microsoft in 1993. It's a way
to create software components that can interact with each other, regardless of the programming language they're
written in. Here are some key points about COM:
● Platform-independent: COM components can work on different operating systems as long as they are
compatible with the COM standard.
● Distributed: COM allows components to be spread across different computers on a network and still
communicate with each other.
● Object-oriented: COM components are built using the principles of object-oriented programming, which
helps with code organization and reusability.
How COM works:
● Interfaces: The core of COM is the concept of interfaces. These are like contracts that define what a
component can do, without specifying how it does it. This allows different programming languages to
interact with the component as long as they understand the interface.
● Implementation: The actual code that implements the functionality of the component is separate from the
interface. This separation allows for flexibility and easier development.
● Clients and Servers: A COM component can act as a client (requesting services) or a server (providing
services) to other components.
Benefits of COM:
● Code reusability: COM components can be reused in different applications, saving development time.
● Interoperability: COM allows components written in different languages to work together.
● Modular design: COM promotes a modular approach to software development, making it easier to
maintain and update.
Web scripting
The Web is one of the most fertile areas for the application of languages at the present time, and readers of
the popular technical press probably believe that is solely concerned with generating interactive Web
pages. Web divides into three areas: (i) forms, (ii) creating pages with enhanced visual effects and user
interaction and (iii) pages 'on the from material held in a database.
1. Write Perl Code:Use a text editor to write Perl code in a plain text file. Save the file with a .pl extension,
which indicates that it contains Perl code.
2. Execute the Perl Script:
❖ Open a command prompt or terminal window on your computer.
❖ Navigate to the directory where the Perl script file is located using the cd command (change
directory).
❖ Once you are in the correct directory, you can execute the Perl script by typing perl followed by the
name of the Perl script file.
❖ For example, if your Perl script file is named hello.pl, you can execute it by typing perl hello.pl and
pressing Enter.
❖ The Perl interpreter will read the Perl code from the script file, interpret it, and execute the
instructions as specified in the code.
2. Assigning Values:
❖ Values can be assigned to variables using the assignment operator (=).
❖ Perl is a dynamically typed language, so you don't need to declare the type of a variable before
assigning a value to it.
❖ Values can be literals (such as numbers, strings, or boolean values) or the result of expressions or
function calls.
Perl distinguishes between singular and plural nouns (names). 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).
In Perl, variable names begin with special characters like '$' for scalar values, '@' for lists, '%' for associative
arrays, and '&' for subroutines, making it easy to understand the type of data each variable holds.
1. my: Declares a lexically scoped variable. Variables declared with "my" are only visible within the block in
which they are declared. They have a limited scope and are typically used for temporary or local variables.
Example:
sub example {
my $local_var = 10;
print $local_var; # This will print 10
}
2. our: Declares a package (global) variable. Variables declared with "our" are accessible from any part of
the package in which they are declared. They have a global scope within the package and can be accessed
by other functions or modules within the same package.
Example:
package MyPackage;
our $global_var = 20;
sub example {
print $global_var; # This will print 20
}
3. local: Temporarily assigns a new value to a global variable within the current scope. Unlike "my" and
"our", "local" does not create a new variable; it only modifies the value of an existing global variable
within the current scope. Once the scope exits, the original value of the global variable is restored.
Example:
our $global_var = 30;
sub example {
local $global_var = 40;
print $global_var; # This will print 40
}
print $global_var; # This will print 30
Scalar data:
Strings:
❖ Strings in Perl are sequences of characters enclosed within single quotes ('') or double quotes ("").
❖ They can contain letters, numbers, special characters, and whitespace.
❖ Perl provides various operators and functions for string manipulation, such as concatenation (.),
interpolation, substring extraction, and pattern matching with regular expressions.
Example:
my $str1 = 'Hello';
my $str2 = "world";
my $concat = $str1 . ' ' . $str2;
print "$concat\n";
Output:
Using the q (quote) and qq (double quote) operators, which allow you to use any character as a quoting character.
For example:
❖ q/any string/ or q{any string} are equivalent to 'any string'
❖ qq/any string/ or qq(any string) are equivalent to "any string"
Example:
my $a=q/kits/;
my $b=q{kits};
my $c='kits';
my $x=qq/kits college/;
my $y=qq{kits college};
my $z="kits college";
print "$a\n";
print "$b\n";
print "$c\n";
print "$x\n";
print "$y\n";
print "$z\n";
Output:
In Perl, the strings 'friday\n' and "friday\n" are different due to how they are interpreted:
1. 'friday\n': This is a single-quoted string literal. In single-quoted strings, escape sequences like \n are not
interpreted. Therefore, 'friday\n' represents the characters 'f', 'r', 'i', 'd', 'a', 'y', '', and 'n'. The backslash (\) is
treated as a literal character, not as an escape sequence. So, the string will print as "friday\n" literally, with
the backslash and 'n' characters visible.
2. "friday\n": This is a double-quoted string literal. In double-quoted strings, escape sequences like \n are
interpreted as special characters. Therefore, "friday\n" represents the characters 'f', 'r', 'i', 'd', 'a', 'y', and a
newline character. The \n sequence is interpreted as a newline character, causing the string to end after
"friday" and start a new line. So, when printed, "friday\n" will display "friday" followed by a newline.
Example:
my $a='friday\n';
my $b="friday\n";
print "$a\n";
print "$b";
Output:
Numbers:
❖ Numbers in Perl can be integers or floating-point numbers.
❖ They can be represented in decimal, hexadecimal (with a leading '0x'), octal (with a leading '0'), or binary
(with a leading '0b') formats.
❖ Perl supports basic arithmetic operations such as addition (+), subtraction (-), multiplication (*), division
(/), and modulus (%).
Example:
my $a=10;
my $b=13.14;
print $a+$b;
Output:
Perl is a loosely typed language, meaning variables do not have strict data types. They can hold either strings or
numbers, and Perl automatically converts between them as needed during operations
Boolean values:
Perl adopts the simple rule that numeric zero, "0" , the special value undef (indicating an uninitialized variable)
and the empty string ("") mean false, and anything else means true
Example:
$a=10;
$b="";
if($a){
print "the value is true";
}
if($b) #this is empty and it won't be executed
{
print "the value is false";
}
Example:
<STDIN>
It is used to read input from the standard input stream, typically provided by the user via the keyboard.
Example:
print "Enter the Number";
$a=<STDIN>;
print "the value of a is $a"
Output:
Scalar expressions:
Scalar data items (whether literals or values of variables) are combined into expressions
using operators.
Operators:
1. Arithmetic Operators
2. String Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
6. Conditional Operators
2. String Operator:
‘x’ operator is used to repeat a string a certain number of times.
Example:
$a="kits\n" x 3;
print $a;
Output:
Auto Increment:
When the auto-increment operator (++) is applied to a string, Perl attempts to find the next string in lexicographic
order. It does this by incrementing the last character of the string. If the last character is a letter, Perl increments it
to the next letter in alphabetical order. If the last character is a digit, Perl increments it as a number. If the last
character is a non-alphanumeric character, Perl increments it to the next character in ASCII order.
Example:
$a="abc";
print ++$a."\n";
$b="abc4";
print ++$b."\n";
Output:
Unary minus:
when the unary minus operator is applied to a string that cannot be interpreted as a number, it simply treats the
string as a string and prepends a minus sign to it.
Example:
$a='kits';
print -$a;.
Output:
-kits
Comparison Operators:
The comparison operators indeed return a value of 1 when the comparison is true, and an empty string (which is
considered false in Perl context) when the comparison is false.
1. Equality Operators:
❖ ==: Checks if two values are numerically equal.
❖ !=: Checks if two values are not numerically equal.
❖ eq: Checks if two strings are equal.
❖ ne: Checks if two strings are not equal.
2. Numeric Comparison Operators:
❖ <: Checks if the left operand is numerically less than the right operand.
❖ >: Checks if the left operand is numerically greater than the right operand.
❖ <=: Checks if the left operand is numerically less than or equal to the right operand.
❖ >=: Checks if the left operand is numerically greater than or equal to the right operand.
3. String Comparison Operators:
❖ lt: Checks if the left operand is stringwise less than the right operand.
❖ gt: Checks if the left operand is stringwise greater than the right operand.
❖ le: Checks if the left operand is stringwise less than or equal to the right operand.
❖ ge: Checks if the left operand is stringwise greater than or equal to the right operand.
4. Three-way Comparison Operator:
❖ <=>: Compares two numeric values and returns -1 if the left operand is less than the right, 0 if they
are equal, and 1 if the left operand is greater than the right.
Program:
$a=10;
$b=10;
print "Equal to".($a==$b),"\n";
print "Not equal to".($a!=$b)."\n";
print "Greater than".($a>$b)."\n";
print "less than".($a<$b)."\n";
print "Greater than or equal ".($a>=$b)."\n";
print "less than or equal ".($a<=$b)."\n";
$x="kits";
$y="college";
print "equal to".($x eq $y)."\n";
print "Not equal to ".($x ne $y)."\n";
print "Less than ".($x lt $y)."\n";
print "Greater than ".($x gt $y)."\n";
print "Less than or equal to ".($x le $y)."\n";
print "Greater than or equal to ".($x ge $y)."\n";
print "Three way comparison ".(10<=>10)
Output:
Logical Operators:
Perl provides logical operators to perform boolean operations.
1. Logical AND (&&): Returns true if both operands are true.
2. Logical OR (||): Returns true if at least one of the operands is true.
3. Logical NOT (!): Returns true if the operand is false and false if the operand is true.
Example:
my $num1 = 10;
my $num2 = 5;
if ($num1 > 5 && $num2 < 10)
{
print "Both conditions are true\n";
}
else
{
print "At least one condition is false\n";
}
my $str1 = "apple";
my $str2 = "banana";
if ($str1 eq "apple" || $str2 eq "banana")
{
print "At least one condition is true\n";
}
else
{
print "Both conditions are false\n";
}
my $flag = 1;
if (!$flag) {
print "Flag is false\n";
} else {
print "Flag is true\n";
}
Output:
Conditional Operators:
A conditional expression is one whose value is chosen from two alternatives at run-time
depending on the outcome of a test.
Example:
$a=100;
print $a= ($a < 0) ? 0 : $a;
Output:
100
Control structures
Control structures are fundamental building blocks that dictate the flow of execution within a program. They
provide a way to make decisions based on conditions and repeat code blocks as needed, allowing you to create
programs that respond to different situations and perform tasks efficiently.
if:
Example:
my $age = 25;
if ($age >= 18) {
print "You are eligible to vote.\n";
}
Output:
if else:
Example:
my $age = 15;
if ($age >= 18)
{
print "You are eligible to vote.\n";
}
else
{
print "You are not eligible for vote";
}
Output:
elsif (else if):
Example:
my $day = "Sunday";
if ($day eq "Saturday")
{print "It's the weekend!\n";
}
elsif ($day eq "Sunday")
{print "Enjoy your Sunday!\n";
}
else
{print "Back to work tomorrow.\n";}
Output:
unless:
Example:
my $is_registered = 0;
unless ($is_registered) {
print "Please register to participate.\n";
}
Output:
Please register to participate.
This code executes the block only if $is_registered is false (0).
unless-else:
my $a = 25;
unless ($a<=18) {
print "You are eligible for vote\n";
}
else
{
print "You are not eligible for vote";
}
Output:
Repetition (Looping):
While:
❖ The while loop repeatedly executes a code block as long as a specified condition remains true.
❖ The condition is evaluated at the beginning of each iteration.
❖ Once the condition becomes false, the loop terminates.
Example:
This code prints numbers from 1 to 5 using a while loop that continues as long as $a is less than or equal to 5.
my $a=1;
while($a<5)
{
print "kits college\n";
$a++;
}
Output:
Until loop:
❖ The until loop is the opposite of while.
❖ It executes a code block repeatedly until a specified condition becomes true.
❖ The condition is evaluated at the beginning of each iteration.
❖ Once the condition becomes true, the loop terminates.
Example:
my $a="";
until($a eq "Deepak")
{
print "Enter the password ";
chomp($a=<STDIN>)
}
print "Welcome";
Output:
For loop:
❖ The for loop provides two ways to iterate:
➢ Over a list of elements (@list).
➢ Using a counter variable with a start, end, and increment value.
❖ In the list iteration, $_ refers to the current element in the list.
Example-1:
my @fruits = ("apple", "banana", "orange");
for (@fruits) {
print "$_ "; # $_ refers to the current element in the list
}
print "\n";
Output:
Example- 2:
# Iterating with a counter
for (my $i = 1; $i <= 3; $i++) {
print "$i ";
}
print "\n";
Output:
123
foreach loop:
The foreach loop is a convenient way to iterate through the elements of a list or hash in Perl. It provides a concise
syntax for processing each item and is often preferred over traditional for loops when working with collections.
Example:
my @fruits = ("apple", "banana", "orange");
foreach my $fruit (@fruits) {
print "I like to eat $fruit.\n";
}
Output:
list:
The list is a sequence of scalar values. However, the list is not a data structure in Perl. There are limited operations
that can be performed on the list in Perl. Since no variable refers to this list, lists cannot be used for operations
other than printing.
Example:
(10, 20, 30);
("this", "is", "a", "list", "in", "perl");
Example:
print("List declared and printed: ");
print join(' ', 10, 20, 30, 40, 50);
print "\n\n" ;
# Complex lists
print("complex", 10, 20, "list");
print("\n\n");
Output:
Arrays:
Arrays are ordered collections of elements that can hold various data types (numbers, strings, even other arrays or
hashes). They are a fundamental data structure in Perl, allowing you to group and manage related data efficiently.
The name of such a variable always starts with an @, e.g. @days_of_week
The association between arrays and lists is a close one: an array stores a collection, and a list is a collection, so it is
natural to a list to an array,
e.g. @rainfa11 = (1.2, 0.4, 0.3, 0.1, 0, 0, 0);
A list can occur as an element of another list.
Example:
@foo = (1,2, 3, "string");
@foobar = (4, 5, @foo, 6);
gives foobar the value (4,5,1,2,3,"string",6)
Using the qw function: This function is useful for creating arrays with multiple whitespace-separated elements:
Example:
my @colors = qw(red green blue);
print "Primary colors: ";
foreach my $color (@colors)
{
print "$color ";
}
print "\n";
Output:
Accessing elements:
Example:
@fruits=("apple","banana","orange");
my $first_fruit = $fruits[0]; # $first_fruit will be "apple"
my $last_item = $fruits[-1]; # $last_item will be "blue" (negative index for the last element)
print $first_fruit." ";
print $last_item;
Output:
Slice:
Slicing an array in Perl allows you to extract a specific portion of elements from an existing array.
1. Using Square Brackets with Start and End Indexes:
This method provides a concise way to extract a subset of elements based on their index positions.
Syntax:
@sliced_array = @original_array[@start_index..@end_index];
Example:
my @fruits = ("apple", "banana", "orange", "mango", "pineapple");
my @sliced_fruits = @fruits[1..3]; # Extract elements from index 1 (inclusive) to 3 (exclusive)
print "@sliced_fruits"; # Output: @sliced_fruits: banana orange
Hashes:
hashes (also sometimes called associative arrays) are powerful data structures used to store collections of key-
value pairs. Unlike arrays where elements are accessed by numerical indexes, hashes provide a more flexible way
to manage data using descriptive keys.
Creating Hashes:
You can create hashes using curly braces {}, separating keys and values with colons =>:
Example:
my %fruits = ("apple" => "red", "banana" => "yellow", "orange" => "orange");
The percent sign % at the beginning indicates it's a hash.
Accessing Elements:
my $apple_color = $fruits{"apple"}; # $apple_color will be "red"
Iterating over Hashes:
There are two common ways to iterate through the key-value pairs of a hash:
1. Using foreach: This loop iterates over the keys of the hash, and within the loop, you can access the
corresponding values:
Example: foreach $fruit(keys %fruits)
{
print "$fruit"." ";
}
2. Using each function: This function returns a key-value pair at each iteration:
Example:
while (($key, $value) = each %fruits) {
print "$key: $value\n";
}
Hash Operations:
❖ exists $hash{$key}: Checks if a specific key exists in the hash.
❖ delete $hash{$key}: Removes a key-value pair from the hash.
❖ %new_hash = %old_hash: Creates a new hash by copying all key-value pairs from the old hash.
Pattern Matching:
Regular expressions in Perl (regex) are powerful tools for pattern matching and text manipulation. They allow you
to search for specific patterns within strings and perform various operations such as finding, replacing, or
extracting text based on those patterns.
Some common elements and syntax used in regular expressions in Perl:
1. Literal Characters: Regular expressions can include literal characters that match themselves. For
example, the regex /hello/ matches the string "hello" exactly.
Example:
my $text = "This is a sample text string.";
if ($text =~ /z/)
{
print "'s' found in the string.\n";
}
else
{
print "text not found\n";
}
if ($text =~ /is/)
{
print "'is' found in the string.\n";
}
Output:
text not found
'is' found in the string.
2. Metacharacters: Metacharacters are special characters with a specific meaning in regular expressions.
Some common metacharacters include:
❖ . (dot): Matches any single character except newline.
Example :
$text = "This is a string with special characters!"; if ($text =~ /e./)
{
print "Matched 'e' followed by any character (except newline)\n";
}
❖ *: Matches zero or more occurrences of the preceding character or group.
Example:
$text = "aaabbbcccc";
if ($text =~ /a*bc/) { # Matches "a" zero or more times followed by "bc"
print "Matched 'a' zero or more times followed by 'bc'\n";
}
❖ +: Matches one or more occurrences of the preceding character or group.
Example:
$text = "color, colour, flavor";
if ($text =~ /col+or/)
{
# Matches "col" one or more times followed by "or"
print "Matched 'col' one or more times followed by 'or'\n";
}
4. Anchors: Anchors are used to specify positions within the string. Common anchors include:
❖ ^: Matches the start of the string.
Example:
$text = "Starting with capital";
if ($text =~ /^Starting/)
{
print "Matched 'Starting' at the beginning"
}#This will only match "Starting with capital" (not "Another string starting with something else").
❖ $: Matches the end of the string.
Example:
$text = "String ending with dot.";
if ($text =~ /dot\.$/)
{
print "Matched 'dot.' at the end"
}
#This will only match "String ending with dot." (not "String with something else").
❖ \b: Matches a word boundary.
5. Character Classes: Character classes specify a set of characters that can match at a particular position in
the string. They are enclosed in square brackets [ ] and match any single character within the brackets.
6. Modifiers: Modifiers are added after the closing delimiter of the regular expression and affect how the
pattern matching is performed. Some common modifiers include:
❖ i: Case-insensitive matching.
❖ g: Global matching (find all matches).
❖ m: Treat the string as multiple lines.
❖ s: Treat the string as a single line.
Shorthand
1. \d: Matches any decimal digit (0-9).
Example:
$text = "Phone: 123-456-7890";
if ($text =~ /phone:\s+\d{3}-\d{3}-\d{4}/)
{
print "Matched phone number format"
}
# This matches phone numbers with three digits separated by hyphens.
2. \w: Matches any "word" character, which includes alphanumeric characters (a-z, A-Z, 0-9) and the
underscore character (_).
Example:
$text = "This is a test_string";
if ($text =~ /\b\w+\b/)
{
print "Matched whole word"
} # This will match each word individually ("This", "is", "a", "test_string").
3. \s: Matches any whitespace character, including space, tab, newline, carriage return, and form feed.
Example:
$text = "Name\tAge\nCity";
if ($text =~ /\w+\s+\w+\s+\w+/)
{
print "Matched name separated by whitespace"
}
#This matches the format "Name Age City" with any amount of whitespace between them.
Capitalized versions negate the meaning:
1. \D: Matches any character that is not a digit.
2. \W: Matches any character that is not a "word" character.
3. \S: Matches any character that is not whitespace.
Regular expressions in Perl are enclosed in forward slashes /regex/ and can be used with various built-in functions
like =~ operator for matching, s/// operator for substitution, and m// operator for pattern matching.
Greedy and non-Greedy quantifiers:Regular expressions (regex) support both greedy and non-greedy (also
known as lazy) quantifiers. These quantifiers determine how much of the input string is consumed by the regex
during pattern matching.
Greedy Quantifiers
Greedy quantifiers match as much of the input string as possible. The default behavior in Perl regex is greedy.
Examples of Greedy Quantifiers:
1. * : Matches 0 or more times.
2. + : Matches 1 or more times.
3. ? : Matches 0 or 1 time.
4. {n} : Matches exactly n times.
5. {n,} : Matches at least n times.
6. {n,m} : Matches between n and m times.
Example:
my $text = "The quick brown fox jumps over the lazy dog.";
$text =~ /(.*)/;
print $1; # Output: The quick brown fox jumps over the lazy dog.
In this example, (.*) is greedy and matches the entire string.
Non-Greedy Quantifiers
Non-greedy quantifiers match as little of the input string as possible. They are indicated by appending a ? to the
greedy quantifier.
Examples of Non-Greedy Quantifiers:
1. *? : Matches 0 or more times, but as few as possible.
2. +? : Matches 1 or more times, but as few as possible.
3. ?? : Matches 0 or 1 time, but as few as possible.
4. {n}? : Matches exactly n times.
5. {n,}? : Matches at least n times, but as few as possible.
6. {n,m}? : Matches between n and m times, but as few as possible.
Example:
my $text = "The quick brown fox jumps over the lazy dog.";
$text =~ /(.*?) /;
print $1; # Output: The
In this example, (.*?) is non-greedy and matches as little of the string as possible before the first space.
Use greedy quantifiers when you want to match as much text as possible, and use non-greedy quantifiers when
you need to match the smallest possible amount of text to satisfy the pattern.
subroutines:
Subroutines, also known as functions or methods in other programming languages, are a fundamental concept in
Perl for code reusability, modularity, and organization. Here's a breakdown of subroutines in Perl:
What are Subroutines?
❖ Subroutines are reusable blocks of code that perform specific tasks.
❖ You can define a subroutine once and then call it from different parts of your program whenever you need
that functionality.
Defining Subroutines:
❖ The sub keyword is used to define a subroutine.
❖ The subroutine name follows the sub keyword and should adhere to Perl's identifier naming conventions
(letters, digits, and underscores, starting with a letter).
Example:
sub sample {
print "Hello, name!\n";
}
sample;
Output:
UNIT - IV
Advanced perl
Finer points of looping:
Perl offers several looping constructs for iterating over sequences of data or executing code repeatedly.
for loop:
Example:
for ($i = 0; $i < 5; $i++) {
print "Iteration: $i\n";
}
Output:
while loop:
Example:
$count = 0;
while ($count < 3) {
print "Count: $count\n";
$count++;
}
Output:
do …while loop:
Example:
$number = 10;
do {
print "Number: $number\n";
$number--;
} while ($number >= 0);
Output:
foreach loop:
@fruits = ("apple", "banana", "orange");
foreach $fruit (@fruits) {
print "Fruit: $fruit\n";
}
Output:
continue:
The continue block in Perl is used in conjunction with while, until, for, and foreach loops. It allows you to specify
a block of code that will execute after each iteration of the loop, just before the condition is re-evaluated for the
next iteration.
Example:
my @numbers = (1, 2, 3, 4, 5, 6);
foreach my $num (@numbers) {
next if ($num % 2 == 0); # Skip even numbers
print "$num\n";
} continue {
}
next:
The next statement is used to skip the rest of the current iteration and proceed with the next iteration of the loop. It
is similar to continue in other languages.
Example:
my @numbers = (1, 2, 3, 4, 5, 6);
foreach my $num (@numbers) {
if ($num % 2 == 0) {
next; # Skip even numbers
}
print "$num\n";
}
print "Loop completed.\n";
redo:
The redo statement restarts the current iteration of the loop without evaluating the loop condition again. It is useful
when you want to retry the current iteration.
Example:
my $i = 0;
while ($i < 5) {
$i++;
if ($i == 3) {
print "Redoing iteration for $i\n";
redo;
}
print "In loop: $i\n";
}
Example:
$i=2;
$f=10.5;
$c='A';
$packed_data=pack("ifA",$i,$f,$c);
print $packed_data."\n";
($test,$test1,$test2)=unpack("ifA",$packed_data);
print "$test,$test1,$test2";
unpack Function
The unpack function is the reverse of pack. It takes a binary string and a template and converts the binary string
back into a list of values.
Syntax:
@list = unpack(TEMPLATE, BINARY_STRING);
TEMPLATE: A string that specifies the format to use for each part of the binary string.
BINARY_STRING: The binary string to be unpacked.
Example:
($test,$test1,$test2)=unpack("ifA",$packed_data);
print "$test,$test1,$test2";
Practical Usage
Packing a Network Packet
my $packet = pack("C4n", 192, 168, 1, 1, 8080);
# C4 means 4 unsigned chars for IP address
# n means a 16-bit unsigned short for port number
File System:
Perl provides extensive support for interacting with the filesystem. This includes reading from and writing to files,
manipulating file and directory structures, and querying file attributes.
Filehandles:
❖ A filehandle is a named variable that acts as a connection to a physical file.
❖ To read from or write to a file, you first need to open it using the open function. Always check if the file
was opened successfully.
File Modes:
❖ There are three basic file modes:
➢ <: Read mode - Opens an existing file for reading.
➢ >: Write mode - Opens a file for writing. If the file exists, its contents are overwritten. If it doesn't
exist, it's created.
➢ >>: Append mode - Opens a file for appending data to the end. If the file doesn't exist, it's created.
Example:
Opening a File
# Opening a file for reading
open(my $fh, '<', 'filename.txt') or die "Cannot open file: $!";
# Opening a file for writing (creates a new file or truncates an existing one)
open(my $fh, '>', 'filename.txt') or die "Cannot open file: $!";
# Opening a file for appending (creates a new file if it doesn't exist)
open(my $fh, '>>', 'filename.txt') or die "Cannot open file: $!";
Closing a File
close($fh) or die "Cannot close file: $!";
Writing to a File
Writing Line by Line
open(my $fh, '>', 'filename.txt') or die "Cannot open file: $!";
print $fh "First line\n";
print $fh "Second line\n";
close($fh);
eval:
The eval function is a powerful and versatile tool that allows you to execute Perl code contained in a string at
runtime or to trap runtime errors. There are two primary forms of eval:
String form: Executes Perl code contained in a string.
Block form: Evaluates a block of code and catches any runtime errors.
String Form of eval
The string form of eval is used to execute a string of Perl code. This is useful when you need to construct and
execute Perl code dynamically.
Example:
my $code = '$x = 10; $y = 20; $z = $x + $y;';
eval $code;
print "The result is: $z\n"; # Output: The result is: 30
In this example, the string $code contains Perl code that is executed by eval. After execution, the variables $x, $y,
and $z are available in the current scope.
Block Form of eval
The block form of eval is used to trap runtime errors within a block of code. This is particularly useful for
exception handling.
Syntax:
eval {
# Code that might throw an exception
};
Example:
eval {
my $result = 10 / 0; # Division by zero error
};
if ($@) {
print "An error occurred: $@\n";
}
In this example, the division by zero generates a runtime error. The error is caught by eval, and the error message
is stored in $@.
Data structures:
Arrays of arrays:
An array of arrays (also known as a multidimensional array) is essentially an array where each element is a
reference to another array. This allows you to create complex data structures like matrices, tables, or any other
form of nested lists.
Creating an Array of Arrays:
Using Array References
Example:
my @row1 = (1, 2, 3);
my @row2 = (4, 5, 6);
my @row3 = (7, 8, 9);
# Create an array of array references
my @matrix = (\@row1, \@row2, \@row3);
In this example, @matrix is an array where each element is a reference to one of the row arrays (@row1, @row2,
and @row3).
the \@ syntax is used to create a reference to an array.An array reference is essentially a pointer to an array.
Instead of working directly with the array, you work with the reference, which allows you to easily create complex
data structures like arrays of arrays.
Direct Initialization
You can also initialize an array of arrays directly:
Example:
my @matrix = (
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
);
Here, each sub-array (row) is created using anonymous array references ([...]), which are directly nested within
@matrix.
Modifying Elements
You can modify elements in an array of arrays by directly accessing them:
$matrix[1][2] = 10; # Change the third element of the second row to 10
print $matrix[1][2]; # Output: 10
Accessing Elements
To access elements in an array of arrays, you need to dereference the array references.
Accessing an Entire Row
my $first_row_ref = $matrix[0];
print "@$first_row_ref\n"; # Output: 1 2 3
Accessing Individual Elements
To access individual elements, you use double indexing:
print $matrix[0][1]; # Output: 2
print $matrix[2][0]; # Output: 7
Here, $matrix[0][1] accesses the second element of the first row, and $matrix[2][0] accesses the first element of
the third row.
Iterating Over an Array of Arrays
You can iterate over the rows and elements using nested loops.
Iterating Over Rows
foreach my $row_ref (@matrix) {
print "@$row_ref\n";
}
Iterating Over Rows and Columns
foreach my $row_ref (@matrix) {
foreach my $element (@$row_ref) {
print "$element ";
}
print "\n";
}
Example Program on Arrays of arrays:
# Creating a 2D matrix
my @matrix = (
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
);
# Accessing an element
print "Element at (1, 2): $matrix[1][2]\n"; # Output: 6
# Modifying an element
$matrix[1][2] = 10;
print "Modified element at (1, 2): $matrix[1][2]\n"; # Output: 10
hashes of hash:
hash of hashes is a complex data structure where each value in a hash is itself a reference to another hash. This
allows for the creation of nested associative arrays, which can be used to represent more complex data structures
such as records, trees, or tables.
Creating a Hash of Hashes
Using Hash References
Example:
# Create individual hashes
my %hash1 = (name => 'John', age => 30);
my %hash2 = (name => 'Jane', age => 25);
my %hash3 = (name => 'Doe', age => 40);
# Create a hash of hash references
my %hoh = (
person1 => \%hash1,
person2 => \%hash2,
person3 => \%hash3,
);
In this example:
❖ %hash1, %hash2, and %hash3 are individual hashes.
❖ \%hash1, \%hash2, and \%hash3 create references to these hashes.
❖ %hoh is a hash where each key (person1, person2, person3) points to a reference to another hash.
Direct Initialization
You can also initialize a hash of hashes directly:
Example:
my %hoh = (
person1 => {
name => 'John',
age => 30,
},
person2 => {
name => 'Jane',
age => 25,
},
person3 => {
name => 'Doe',
age => 40,
},
);
Advantages of packages:
1. Group related code for better readability and maintainability.
2. Prevent naming clashes with other parts of your code.
3. Create reusable code components.
Modules:
Modules are files containing Perl code, encapsulated into a package, which can be reused across different scripts
and applications.
They usually end with a .pm extension.
A module starts with a package declaration and ends with a true value (usually 1;)
Modules are included in scripts using the use,use implicitly calls import method.
Modules can export functions and variables using Exporter module.
To export symbols, set up @EXPORT or @EXPORT_OK arrays and inherit from Exporter
Example:
package MyModule;
use Exporter 'import';
our @EXPORT = qw(hello);
our @EXPORT_OK = qw(goodbye);
sub hello {
print "Hello\n";
}
sub goodbye {
print "Goodbye\n";
}
1;
Another program:
use MyModule; # Imports hello
hello();
use MyModule qw(goodbye); # Imports goodbye explicitly
goodbye();
❖ The @ISA array in Perl is used for establishing inheritance in object-oriented Perl. It allows one package to
inherit methods and properties from another package.
***package is a namespace for organizing code, while a module is a file that typically contains a package and is
designed for reuse and distribution.
ON WINDOWS:
#!/usr/bin/perl
print "This is Windows\n";
system("dir");
In both cases, the system function is used to execute a system command. The command itself differs (ls -l for
UNIX and dir for Windows), but the Perl code structure remains the same.
Here we describe a collection of facilities that are common to the UNIX and NT implementations of Perl:
Environment variables:
In Perl, environment variables are managed through a special hash called %ENV. Each key in this hash
corresponds to an environment variable name, and the associated value is the value of that environment variable.
By accessing %ENV, a script can read and modify environment variables.
Example:
print "PATH is $ENV{PATH}\n";
Perl provides a way to temporarily change the value of an environment variable within a specific scope using the
local keyword. The local keyword temporarily changes the value of a global variable (including elements of arrays
and hashes) within a block, and restores the original value when the block is exited. This can be particularly useful
for making temporary changes to environment variables.
Example:
{
local $ENV{PATH} = "/temporary/path/bin:$ENV{PATH}";
}
Shell commands:
Perl provides two main ways to execute shell commands from within a script: using the built-in system function
and using backticks (`) or the qx// operator, often referred to as "quoted execution."
system function:
Runs a command in the system shell.it does not capture the command's output. Instead, it returns the exit status of
the command.
The use of && rather than || as the connector, this is because shell commands returns zero to denote success and a
non-zero value to denote failure
Example:
system("mkdir test_directory") and die “success”
if ($? == -1) {
print "Failed to execute: $!\n";
} else {
printf "Command exited with value $?;
}
exec:
The exec function in Perl is used to replace the current process with a new process, running the specified
command. Unlike the system function, which runs a command and then returns control to the Perl script, exec
never returns. Once exec is called, the current script stops executing, and the new command takes over the process
completely.
Example:
exec "perl -w scr2.pl" or die "Exec failed\n"; # the -w switch is used to enable warnings
For example, a Perl application can interact with a web server to perform actions like submitting a query via a web
form. This process involves sending the query to a CGI program on the server, which processes the request,
retrieves the relevant information, formats it into an HTML page, and returns the page to the client. Similarly, Perl
applications can connect to POP3 mail servers to check for unread messages.
Scripting languages like Perl simplify these operations by abstracting their complexities, particularly through
specialized modules. The LWP (Library for WWW in Perl) collection of modules is a prime example, as it makes
these interactions straightforward and requires minimal code compared to languages like C.
In summary, Perl and its LWP modules enable the creation of powerful "Internet-aware" applications that can
automate interactions with various internet services, streamlining tasks that would otherwise require extensive
manual effort or complex coding.
LWP::Simple
Creating "Internet-aware" applications in Perl can be done using the LWP::Simple module, which is part of the
larger LWP (Library for WWW in Perl) suite. LWP::Simple provides easy-to-use functions for fetching
documents from the web without needing to understand the complexities of HTTP protocol handling.
You can install it from CPAN if it's not already available:
cpan install LWP::Simple
The LWP::Simple module provides several functions for fetching web content. The most commonly used
functions are:
get($url): Fetches the document at the specified URL and returns it as a string.
getprint($url): Fetches the document at the specified URL and prints it to standard output.
getstore($url, $file): Fetches the document at the specified URL and stores it in the specified file.
Example: Fetching and Printing Web Page Content
use strict;
use warnings;
use LWP::Simple;
# URL of the web page to fetch
my $url = 'http://www.example.com';
# Fetch the content of the URL
my $content = get($url);
# Check if the content was successfully fetched
if (defined $content) {
print "Content of $url:\n";
print $content;
} else {
die "Couldn't get $url";
}
Example: Saving Web Page Content to a File
use strict;
use warnings;
use LWP::Simple;
# URL of the web page to fetch
my $url = 'http://www.example.com';
# File to save the content
my $file = 'example.html';
# Fetch the content and store it in the file
my $status = getstore($url, $file);
# Check the status of the operation
if ($status == 200) {
print "Content saved to $file\n";
} else {
die "Failed to get $url: HTTP status $status";
}
LWP::UserAgent
Purpose: LWP::UserAgent provides a more comprehensive and configurable interface for web requests. It allows
detailed control over HTTP requests and responses, making it suitable for more complex web interactions.
Features:
❖ Full control over HTTP methods (GET, POST, PUT, DELETE, etc.).
❖ Ability to set custom headers, handle cookies, follow redirects, and use proxies.
❖ Configurable timeouts and SSL/TLS support.
❖ Can handle advanced use cases like authentication, multipart forms, and more.
Common Methods:
Security issues:
Taint Checking in Perl
When taint checking is enabled, Perl tracks all data coming from outside the program (e.g., user input,
environment variables, command line arguments) and marks it as "tainted." Tainted data cannot be used directly in
operations that affect the system (e.g., system calls, file operations) without being first sanitized.
Tainted Data
● Sources of Tainted Data: Any data that comes from outside the program is considered tainted. This
includes:
To enable taint checking in a Perl script, you use the -T switch on the command line or include it in the shebang
line.
Example Program:
#!/usr/bin/perl -T
use strict;
use warnings;
# Get user input
print "Enter a file name: ";
chomp(my $filename = <STDIN>);
# Example of tainted data (user input)
if ($filename =~ /^([a-zA-Z0-9_\-\.]+)$/) {
$filename = $1; # Untainting the data by capturing in a regex group
} else {
die "Invalid file name: $filename\n";
}
# Open the file (safe operation after untainting)
open(my $fh, '<', $filename) or die "Could not open file '$filename': $!\n";
while (my $line = <$fh>) {
print $line;
}
close($fh);
Advantages:
Security: Taint checking prevents malicious input from being executed as system commands or affecting critical
files.
Robustness: By ensuring data is validated and sanitized, scripts are more reliable and less prone to unexpected
behavior.
Safe module:
Taint checking provides security for code you have written which uses potentially unsafe
data from outside. A different situation arises if you have to execute code that comes from
an unknown or untrusted source. The Safe module allows you to set up 'Safe objects':
each of these is a compartment (or 'sand box') in which untrusted code can be executed in
isolation from the rest of your program. A Safe object has a namespace which is rooted at
a specific level in the package hierarchy, so the code executed cannot access variables
declared and used at a higher level in the hierarchy.