0% found this document useful (0 votes)
57 views110 pages

SL Unit-Iii

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

SL Unit-Iii

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

UNIT – III

3.1 Introduction to PERL and Scripting

3.1.1 Introduction

Perl is a programming language which was originally developed for script manipulation. But now
Perl is used for a variety of purpose including web development, GUI development, system
administration and many more. It is a stable, cross platform programming language.

For web development, Perl CGI is used. CGI is the gateway which interacts with the web browser
and Perl in a system.

Perl is a general-purpose, high level interpreted and dynamic programming language. It was
developed by Larry Wall, in 1987. There is no official Full form of the Perl, but still, the most used
expansion is “Practical Extraction and Reporting Language“. Some of the programmers also refer
Perl as the “Pathologically Eclectic Rubbish Lister” Or “Practically Everything Really Likable“.
The acronym “Practical Extraction and Reporting Language” is used widely because Perl was
originally developed for the text processing like extracting the required information from a specified
text file and for converting the text file into a different form. Perl supports both the procedural and
Object-Oriented programming. Perl is a lot similar to C syntactically and is easy for the users who
have knowledge of C, C++.

Its typical use is extracting information from a text file and printing out report for converting a text

file into another form. This is because it got its name after the expression, " Practical Extraction

and Reporting Language".

Programs written in Perl are called Perl scripts, whereas system programs to execute Perl scripts are
called Perl program.

Perl is an interpreted language. When a Perl program run, it is first compiled into a byte code, then it
is converted into machine instructions. So writing something in Perl instead of C saves your time.

It supports most of the operating systems and is listed in Oxford English dictionary. Its concepts and
syntax is taken from many languages like awk, bourne shell, C, sedand even English.
3.1.2 Evolution of PERL

It all started when Larry Wall was working on a task to generate the reports from a lot of text files
which have cross-references. Then he started to use awk for this task but soon he found that it is not
sufficient for this task. So instead of writing a utility for this task, he wrote a new language i.e. Perl
and also wrote the interpreter for it. He wrote the language Perl in C and some of the concepts are
taken from awk, sed, and LISP etc. At the beginning level, Perl was developed only for the system
management and text handling but in later versions, Perl got the ability to handle regular expressions,
and network sockets etc. In present Perl is popular for its ability to handling the Regex(Regular
Expressions). The first version of Perl was 1.0 which released on December 18, 1987. The latest
version of Perl is 5.28. Perl 6 is different from Perl 5 because it is a fully object-oriented
reimplementation of Perl 5.

Perl is a high-level, general-purpose programming language that was created by Larry Wall in 1987.
It was originally designed for text processing, but has since evolved to become a full-featured
programming language that is widely used in web development, system administration, network
programming, and more.

Perl is a popular choice for many programmers because of its versatility and powerful regular
expression support, which makes it ideal for text processing and data manipulation tasks. It also has a
large and active community of developers who have contributed to a vast library of modules and
extensions that can be used to extend the language’s functionality.

One of Perl’s defining features is its“There’s more than one way to do it” philosophy,
which encourages developers to solve problems using their own preferred methods rather than
adhering to strict coding conventions. This can make Perl code more flexible and expressive, but it
can also lead to code that is difficult to read and maintain.

Perl code is typically interpreted, meaning that it is executed directly by the computer without the
need for compilation. This can make development faster and more flexible, but can also lead to
slower execution times for large programs. However, Perl also supports compilation through tools
such as Perlcc and Parrot, which can help to improve performance for larger projects.

3.1.3 PERL Features

o It has a very simple Object-oriented programming syntax.


o It is easily extendible as it supports 25,000 open source modules.
o It supports Unicode.
o It is a cross platform language.
o It includes powerful tools to process text to make it compatible with mark-up languages like
HTML, XML.
o It supports third party database including Oracle, MySQL and many others.
o It is embeddable in other systems such as web servers and database servers.
o It is open source software licensed under GNU.
o Many frameworks are written in Perl.
o It can handle encrypted web data including e-commerce transactions.
o It offers a regular expression engine which is able to transform any type of text.

3.1.4 Why Perl?

Perl has many reasons for being popular and in demand. Few of the reasons are mentioned below:
 Easy to start: Perl is a high-level language so it is closer to other popular programming
languages like C, C++ and thus, becomes easy to learn for anyone.
 Text-Processing: As the acronym “Practical Extraction and Reporting Language” suggest that
Perl has the high text manipulation abilities by which it can generate reports from different text
files easily. Also, it can convert the files into some another form.
 Contained best Features: Perl contains the features of different languages like C, sed, awk,
and sh etc. which makes the Perl more useful and productive.
 System Administration: Due to having the different scripting languages capabilities Perl make
the task of system administration very easy. Instead of becoming dependent on many
languages, just use Perl to complete out the whole task of system administration. In Spite of
this Perl also used in web programming, web automation, GUI programming etc.
 Web and Perl: Perl can be embedded into web servers to increase its processing power and it
has the DBI package, which makes web-database integration very easy.

3.1.5 Programming in Perl

Since the Perl is a lot similar to other widely used languages syntactically, it is easier to code and
learn in Perl. Programs can be written in Perl in any of the widely used text editors
like Notepad++, gedit etc. After writing the program save the file with the extension .pl or .PL To
run the program use perl file_name.pl on the command line.
Example: A simple program to print Welcome to Scripting Languages

Output:
Welcome to Scripting Languages

 Comments: Comments are used for enhancing the readability of the code. The interpreter will
ignore the comment entries and does not execute them. Comments can be of the single line or
multiple lines.
 Single line Comment:
Syntax:
# Single line comment

 Multi-line comment:
Syntax:
= Multi line comments

Line start from = is interpreted as the

starting of multiline comment and =cut is

consider as the end of multiline comment

=cut

 print: It is a function in Perl to show the result or any specified output on the console.
 Quotes: In Perl, you can use either single quotes(‘’)or double quotes(“”). Using single quotes will
not interpolate any variable or special character but using double quotes will interpolates. \n: It is
used for the new line character which uses the backslash (\) character to escape any type of
character.
 /usr/bin/perl: It is actual Perl interpreter binary which always starts with #!. This is used in the
Perl Script Mode Programming.

Note: Perl is case sensitive programming language and that’s why $Girls and $girls are
two different identifiers.

3.1.6 Advantages of Perl


 Perl Provides supports for cross platform and it is compatible with mark-up languages like
HTML, XML etc.
 It is very efficient in text-manipulation i.e. Regular Expression. It also provides the socket
capability.
 It is free and an Open Source software which is licensed under Artistic and GNU General
Public License (GPL).
 It is an embeddable language that’s why it can embed in web servers and database servers.
 It supports more than 25, 000 open source modules on CPAN(Comprehensive Perl Archive
Network) which provide many powerful extensions to the standard library. For example, XML
processing, GUI(Graphical User Interface) and DI(Database Integration) etc.
 Flexibility: Perl is a flexible language that allows programmers to solve problems using a
variety of approaches, making it easy to write code quickly and efficiently.
 Regular expressions: Perl has excellent support for regular expressions, which makes it ideal
for text processing and data manipulation tasks.
 Large library of modules: Perl has a vast library of modules that can be used to extend its
functionality, making it easy to add complex
 features to your programs without having to reinvent the wheel.
 Cross-platform support: Perl runs on a wide range of platforms, including Windows, Linux,
macOS, and more.
 Easy to learn: Perl has a relatively simple syntax and is easy to learn, especially for
programmers who are familiar with other scripting languages.

3.1.7 Disadvantages of Perl


 Perl doesn’t supports portability due to CPAN modules.
 Programs runs slowly and program needs to be interpreted each time when any changes are
made.
 In Perl, the same result can be achieved in several different ways which make the code untidy
as well as unreadable.
 Usability factor is lower when compared to other languages.
 Complex syntax: Perl’s flexibility can also be a disadvantage, as it can lead to code that is
difficult to read and maintain, especially for developers who are new to the language.
 Performance: Perl is an interpreted language, which means that it can be slower than compiled
languages like C or Java for large or computationally intensive programs.
 Legacy code: Because Perl has been around for over 30 years, there is a lot of legacy code
written in earlier versions of the language that may not be compatible with newer versions.
 Security: Perl has some security concerns, such as the possibility of code injection attacks if the
input data is not properly sanitized.

3.1.8 Applications
 One of the major application of Perl language is to processing of text files and analysis of the
strings.
 Perl also used for CGI( Common Gateway Interface) scripts.
 Used in web development, GUI(Graphical User Interface) development.
 Perl’s text-handling capabilities is also used for generating SQL queries

 Perl has a wide range of applications, including:


 Web development: Perl is commonly used for server-side web development, with popular
frameworks such as Catalyst and Dancer.
 Text processing: Perl’s powerful regular expression support makes it ideal for text processing
tasks, such as parsing log files, extracting data from web pages, and manipulating text files.
 System administration: Perl is often used for system administration tasks, such as automating
system backups, managing configuration files, and monitoring system resources.
 Network programming: Perl can be used for network programming, with modules available
for tasks such as sending email, communicating with web services, and building network
protocols.
 Bioinformatics: Perl is widely used in bioinformatics, with popular modules such as BioPerl
providing a powerful toolkit for biological data analysis and manipulation.
 GUI development: Perl can be used for GUI development with toolkits such as Perl/Tk,
allowing developers to create cross-platform desktop applications.
Overall, Perl’s versatility and powerful text processing capabilities make it well-suited for a wide
range of applications, particularly in areas such as web development, system administration, and
bioinformatics.

3.1.9 Scripts and Programs

Scripts and programs are both collections of instructions that tell a computer what to do. However, there
are key differences between them, especially when considering scripting languages.

 Scripts

Definition: A script is a type of program that is usually written in a scripting language and is interpreted
rather than compiled.

Characteristics:

1. Interpreted: Scripts are executed line-by-line by an interpreter rather than being compiled into
machine code.

2. Rapid Development: Scripts are often used for quick development tasks and automation.

3. Usage Context: Commonly used for automating repetitive tasks, manipulating text, managing
system processes, and gluing together other programs or components.

4. Execution: Typically run within the context of a larger application or environment (e.g., a
web server, a game engine, or a shell).

5. Examples: Shell scripts (Bash), Python scripts, JavaScript (for web development), Perl, Ruby.

 Programs

Definition: A program is a set of instructions written in a programming language, which can be compiled
into machine code and executed by the computer’s CPU.

Characteristics:

1. Compiled or Interpreted: Programs can be compiled (e.g., C, C++) or interpreted (e.g.,


Python).

2. Standalone Execution: Programs are often designed to run independently and perform
specific tasks or functions.

3. Complexity: Usually more complex than scripts, often including features like error handling,
user interfaces, and interaction with other software components.
4. Performance: Compiled programs tend to run faster because they are converted directly into
machine code.

5. Usage Context: Used for a wide variety of tasks from operating systems, application
software, games, and complex simulations.

Scripts and programs serve different purposes and are suited for different types of tasks. Scripting
languages provide the flexibility and ease of use needed for rapid development and automation,
while traditional programs written in compiled languages offer the performance and robustness
required for complex applications.

3.1.10 Origin of Scripting

The concept of scripting has evolved alongside the development of computing and programming
languages. Here is a brief history outlining the origin and evolution of scripting:

Early Days: Batch Processing and Shell Scripting

1. 1950s - 1960s:

 Batch Processing: Early computers used batch processing, where a series of


commands were executed without user interaction. Users wrote scripts (then called
"job control languages") to automate tasks like compiling and running programs.

 Job Control Language (JCL): IBM’s JCL for their mainframes is an example of early
scripting to manage job execution and resource allocation.

2. 1970s:

 Unix and Shell Scripting: Unix, developed at Bell Labs, introduced the Unix shell
(sh). The Unix philosophy of combining small, modular programs made shell
scripting powerful. Users could automate tasks by writing scripts in shell languages.

 Bourne Shell (sh): The Bourne shell, introduced in Unix Version 7 (1979), was one of
the earliest powerful scripting environments, allowing for complex automation and
control of Unix systems.

Growth and Development

3. 1980s:

 More Shells: Other shells like C shell (csh) and Korn shell (ksh) were developed, each
adding features and improving scripting capabilities.
 AWK and Sed: AWK and Sed emerged as powerful text processing and pattern
matching tools, enhancing the capability of Unix scripts.

4. 1990s:

 Perl: Larry Wall developed Perl (Practical Extraction and Report Language) in 1987.
Perl became widely used for system administration, web development, and text
processing due to its powerful regular expressions and text manipulation capabilities.

 Tcl and Python: Tcl (Tool Command Language) and Python were introduced. Tcl was
designed for embedding in applications, while Python aimed for readability and
simplicity, becoming a general-purpose scripting language.

 Web Scripting: JavaScript was introduced by Netscape in 1995 to add interactivity to


web pages, marking the beginning of client-side web scripting.

Modern Era

5. 2000s - Present:

 Rise of Python: Python grew in popularity due to its readability, ease of learning, and
versatility. It became a dominant language for scripting, web development, data
science, and automation.

 Ruby: Ruby, introduced in the mid-1990s, gained traction with the release of Ruby on
Rails, a framework that simplified web development.

 JavaScript Dominance: JavaScript became essential for web development with the rise
of AJAX, enabling dynamic and interactive web applications. Node.js (2009)
extended JavaScript to server-side scripting.

 PowerShell: Microsoft introduced PowerShell in 2006, a powerful scripting language


for automating tasks and managing configurations on Windows.

Scripting has its roots in early computing with batch processing and job control languages. It evolved
through the development of Unix shell scripting, the introduction of specialized scripting languages
like Perl and Python, and the widespread use of JavaScript for web development. Today, scripting
languages are integral to various domains, offering powerful tools for automation, integration, and
rapid application development.
3.1.11 Scripting Today

Today, scripting plays a crucial role in various domains of technology, providing flexibility, ease of use,
and rapid development capabilities. Here’s an overview of scripting in the modern context, highlighting its
significance and applications across different fields:

1. Web Development

Client-Side Scripting:

 JavaScript: Remains the dominant language for client-side scripting. Modern frameworks like
React, Angular, and Vue.js enable the development of complex, interactive web applications.

 TypeScript: A superset of JavaScript that adds static typing, improving code quality and
maintainability.

Server-Side Scripting:

 Node.js: Extends JavaScript to the server-side, enabling the use of JavaScript for full-stack
development. Popular frameworks include Express.js and NestJS.

 PHP: Widely used for server-side scripting, particularly in content management systems like
WordPress and Drupal.

 Python: With frameworks like Django and Flask, Python is used for web development,
emphasizing simplicity and rapid development.

2. Automation and System Administration

 Bash: Continues to be the go-to for Unix/Linux system administration tasks.

 PowerShell: A powerful scripting language for Windows system administration, offering


robust automation capabilities.

 Python: Extensively used for automation scripts, given its readability and the vast number of
libraries available (e.g., Ansible for configuration management).

3. Data Science and Machine Learning

 Python: Dominates the data science field with libraries like NumPy, pandas, and scikit-learn
for data manipulation and analysis, and TensorFlow and PyTorch for machine learning.

 R: A scripting language tailored for statistical analysis and data visualization.


4. DevOps and Continuous Integration/Continuous Deployment (CI/CD)

 Shell Scripting (Bash/Powershell): Used for writing build scripts, deployment scripts, and
other automation tasks.

 Python: Popular for writing infrastructure as code (IaC) scripts with tools like Terraform and
for automating CI/CD pipelines.

 Groovy: Used in Jenkins pipelines to define build and deployment stages.

5. Game Development

 Lua: Widely used in game development for scripting game logic, particularly in game engines
like Unity (via the MoonSharp interpreter) and Roblox.

 JavaScript: Utilized in web-based games and for scripting in engines like Phaser.

6. Cloud Computing

 Bash and Python: Commonly used for writing scripts to manage cloud resources in AWS,
Azure, and Google Cloud.

 Terraform (HCL - HashiCorp Configuration Language): Used for scripting infrastructure as


code, enabling the automated setup and management of cloud resources.

7. Internet of Things (IoT)

 Python: Popular for scripting IoT devices due to its ease of use and extensive libraries.

 JavaScript (Node.js): Used in conjunction with frameworks like Johnny-Five for controlling
hardware.

8. Cybersecurity

 Python and Bash: Frequently used for writing scripts for penetration testing, network
scanning, and other security-related tasks.

 PowerShell: Employed in Windows environments for security automation and incident


response.

Modern Trends and Tools in Scripting

 Microservices and APIs: Scripting languages are often used to write and manage
microservices and interact with APIs.
 Serverless Computing: Platforms like AWS Lambda and Azure Functions support scripting
languages like Python, JavaScript, and PowerShell for writing serverless functions.

 Containerization: Docker uses scripting languages (e.g., Dockerfile syntax) for container
orchestration, while Kubernetes uses YAML for configuration scripting.

Scripting languages are indispensable in today’s technology landscape, enabling rapid development,
automation, and integration across diverse fields. The evolution of scripting continues to shape how we
build, deploy, and manage software, ensuring efficiency and adaptability in an ever-changing digital world.

3.1.12 Characteristics of Scripting Languages

Scripting languages possess several distinct characteristics that differentiate them from traditional
programming languages. Here are the key characteristics of scripting languages:

1. Interpreted Execution

 Line-by-Line Execution: Scripting languages are usually interpreted, meaning they are
executed line-by-line by an interpreter rather than being compiled into machine code
beforehand.

 Rapid Feedback: This allows for quick testing and debugging, as changes can be tested
immediately without the need for recompilation.

2. Ease of Use

 Simplified Syntax: Scripting languages often have a simpler and more human-readable syntax
compared to compiled languages, which makes them easier to learn and use.

 High-Level Abstractions: They provide high-level abstractions that allow developers to


perform complex tasks with minimal code.

3. Dynamic Typing

 Type Flexibility: Variables in scripting languages do not require explicit type declarations,
and their types can change at runtime.

 Ease of Development: This reduces boilerplate code and accelerates the development process.

4. Automatic Memory Management


 Garbage Collection: Scripting languages typically include automatic memory management
through garbage collection, which helps prevent memory leaks and simplifies memory
handling for developers.

5. Interactivity and Rapid Development

 Interactive Shells: Many scripting languages offer interactive shells or REPLs (Read-Eval-
Print Loop) that allow developers to execute code snippets and see immediate results.

 Prototyping: They are well-suited for rapid prototyping, allowing developers to quickly
develop and test new ideas.

6. Embeddability

 Embedding Capability: Scripting languages can often be embedded into other applications to
provide scripting capabilities to end-users (e.g., Lua in games, JavaScript in web browsers).

 Extension: Applications can be extended through scripts without modifying the core
application code.

7. Text Processing and Automation

 String Manipulation: Strong support for string manipulation and regular expressions, making
them ideal for text processing tasks.

 Task Automation: They are frequently used for automating repetitive tasks, such as file
manipulation, system administration, and data processing.

8. Platform Independence

 Cross-Platform: Scripts written in scripting languages are generally platform-independent,


running on any system with the appropriate interpreter installed.

 Portability: This makes them highly portable and versatile across different operating systems.

9. Integration and Glue Code

 Interoperability: Scripting languages are often used to integrate and coordinate various
components and applications, acting as "glue code."

 APIs and Libraries: They have extensive standard libraries and support for numerous third-
party libraries, enhancing their functionality and ease of integration.

10. Community and Ecosystem


 Active Communities: Scripting languages usually have vibrant communities that contribute to
a rich ecosystem of libraries, frameworks, and tools.

 Documentation and Support: Extensive documentation and community support make it easier
for developers to find resources and get help.

Examples of Scripting Languages

 Python: Known for its readability, extensive standard library, and use in web development,
automation, data science, and more.

 JavaScript: The backbone of web development, used both on the client-side (in browsers) and
server-side (with Node.js).

 Ruby: Valued for its elegant syntax and used extensively in web development with the Ruby
on Rails framework.

 Perl: Traditionally used for text processing, system administration, and web development.

 PHP: Widely used for server-side web development.

 Lua: Popular in game development and embedded systems for its lightweight footprint and
flexibility.

 Shell Scripting (Bash): Essential for Unix/Linux system administration and automation.

Scripting languages are characterized by their interpreted nature, ease of use, dynamic typing, and strong
support for rapid development and automation. Their ability to integrate disparate systems and automate
complex tasks makes them indispensable in modern software development and system administration.

3.1.13 Uses of Scripting Languages

Scripting languages allow programmers to create interactive websites, browser extensions, and online
games. JavaScript, in particular, makes it easy for programmers to develop cross-platform mobile games.
Popular JavaScript games include Polycraft, Swoop, Hangman, and Little Alchemy.

Scripting languages are also used for data extraction. Python and R are commonly used for data mining.
These languages can be used to import data from Excel spreadsheets, perform calculations, and display the
mined data in a graphical format.

In addition to careers such as JavaScript programmer and Python programmer, there are many jobs
available for those who can program in scripting languages. Examples include data scientist, front-end web
developer, mobile app developer, and software engineer.
 Benefits of Learning a Scripting Language

There are many benefits to learning a scripting language. These include:

 Easy to learn: Scripting languages are high-level programming languages, meaning they are
written to make sense to those who use them. As a result, they are easy to learn and use.

 No compiling: Scripting languages do not need to be compiled before use. This means they
require one less step than other programming languages. It is also easier on the system's
memory to run an interpreter than to compile.

 Cross-platform: Scripting languages are designed to be read by a browser or a remote server,


so they don't require special software to run.

 Open source: Scripting languages are freely available to anyone who wants to use them. All
you have to do is learn.

3.1.14 Web Scripting

The process of creating and embedding scripts in a web page is known as web-scripting. A script
or a computer-script is a list of commands that are embedded in a web-page normally and are
interpreted and executed by a certain program or scripting engine.
 Scripts may be written for a variety of purposes such as for automating processes on a local-
computer or to generate web pages.
 The programming languages in which scripts are written are called scripting language, there
are many scripting languages available today.
 Common scripting languages are VBScript, JavaScript, ASP, PHP, PERL, JSP etc.

 Types of Script :
Scripts are broadly of following two type :
 Client-Side Scripts :
1. Client-side scripting is responsible for interaction within a web page. The client -side scripts
are firstly downloaded at the client-end and then interpreted and executed by the browser
(default browser of the system).
2. The client-side scripting is browser-dependent. i.e., the client-side browser must be scripting
enables in order to run scripts
3. Client-side scripting is used when the client-side interaction is used. Some example uses of
client-side scripting may be :
 To get the data from user’s screen or browser.
 For playing online games.
 Customizing the display of page in browser without reloading or reopening the page.
4. Here are some popular client-side scripting languages VBScript, JavaScript, Hypertext
Processor(PHP).
 Server-Side Scripts :
1. Server-side scripting is responsible for the completion or carrying out a task at the server-end
and then sending the result to the client-end.
2. In server-side script, it doesn’t matter which browser is being used at client -end, because the
server does all the work.
3. Server-side scripting is mainly used when the information is sent to a server and to be
processed at the server-end. Some sample uses of server-scripting can be :
 Password Protection.
 Browser Customization (sending information as per the requirements of client -end
browser)
 Form Processing
 Building/Creating and displaying pages created from a database.
 Dynamically editing changing or adding content to a web-page.
4. Here are some popular server-side scripting languages PHP, Perl, ASP (Active Server Pages),
JSP ( Java Server Pages).

3.1.15 The Universe of Scripting Languages

The universe of scripting languages is vast and diverse, encompassing a wide range of languages
tailored for different tasks and environments. Here’s an overview of some of the most prominent
scripting languages and their key features, uses, and strengths:

1. Python
 Key Features: High-level, interpreted, dynamically typed, extensive standard library, readable
syntax.

 Uses: Web development (Django, Flask), data science (NumPy, pandas), machine learning
(TensorFlow, PyTorch), automation, scripting, and more.

 Strengths: Readability, ease of learning, versatility, strong community support.

2. JavaScript

 Key Features: Interpreted, event-driven, prototype-based, runs in web browsers and on


servers (Node.js).

 Uses: Client-side web development (React, Angular, Vue.js), server-side development


(Node.js), mobile app development (React Native), game development.

 Strengths: Ubiquity in web development, large ecosystem, asynchronous programming


capabilities.

3. Bash

 Key Features: Command language for Unix/Linux systems, text-based, scriptable.

 Uses: System administration, task automation, shell scripting, managing processes.

 Strengths: Integration with Unix/Linux systems, powerful command-line utilities, simplicity


for automating tasks.

4. PowerShell

 Key Features: Command-line shell and scripting language, integrates with .NET, object-
oriented.

 Uses: Windows system administration, automation, configuration management, task


automation.

 Strengths: Integration with Windows systems and applications, robust scripting capabilities,
object-oriented approach.

5. Perl

 Key Features: Interpreted, dynamic typing, strong text processing capabilities, extensive
regular expression support.
 Uses: Text processing, system administration, web development (legacy), bioinformatics.

 Strengths: Powerful text manipulation, mature ecosystem, versatility.

6. Ruby

 Key Features: Interpreted, object-oriented, concise syntax, dynamic typing.

 Uses: Web development (Ruby on Rails), automation, scripting, prototyping.

 Strengths: Elegant syntax, strong web development framework (Rails), active community.

7. PHP

 Key Features: Server-side scripting, embedded in HTML, dynamic typing, interpreted.

 Uses: Web development, content management systems (WordPress, Drupal), server-side


applications.

 Strengths: Wide adoption in web development, easy integration with HTML, extensive web-
specific functionalities.

8. Lua

 Key Features: Lightweight, embeddable, interpreted, procedural.

 Uses: Game development (e.g., in Unity, Roblox), embedded systems, scripting within
applications.

 Strengths: Small footprint, fast execution, ease of embedding into other applications.

9. R

 Key Features: Interpreted, designed for statistical computing, strong data visualization
capabilities.

 Uses: Statistical analysis, data visualization, data science, research.

 Strengths: Specialized for statistics, extensive libraries for data analysis and visualization.

10. TypeScript

 Key Features: Superset of JavaScript, static typing, transpiles to JavaScript.

 Uses: Large-scale JavaScript applications, front-end and back-end development (Node.js),


mobile apps.
 Strengths: Type safety, better tooling and debugging, improves JavaScript code quality.

11. Groovy

 Key Features: Interpreted, optionally typed, integrates with Java, concise syntax.

 Uses: Scripting for the JVM, build automation (Gradle), CI/CD pipelines (Jenkins).

 Strengths: Seamless integration with Java, ease of use, suitable for scripting and quick
prototyping.

12. Shell Scripting (sh, csh, ksh)

 Key Features: Command language for Unix/Linux systems, text-based, scriptable.

 Uses: System administration, task automation, batch processing.

 Strengths: Integration with Unix/Linux systems, variety of shells for different needs,
simplicity for repetitive tasks.

 Emerging and Specialized Scripting Languages

 Swift (for scripting): Apple's language that is gaining traction for server-side scripting and
automation.

 Julia: High-performance language for technical computing and data science.

 HCL (HashiCorp Configuration Language): Used for defining infrastructure as code in tools
like Terraform.

The universe of scripting languages is rich and varied, with each language offering unique strengths
and capabilities tailored to specific tasks and environments. Whether for web development, system
administration, automation, data science, or embedded systems, scripting languages provide the tools
needed to quickly and efficiently accomplish a wide range of tasks. Their flexibility, ease of use, and
powerful features continue to make them essential in modern computing.

3.2 PERL

3.2.1 PERL - Names and Values


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). A notable characteristic of Perl is that variable names start with a special character that
denotes the kind of thing that the name stands for - scalar data ($), array (@), hash (%), subroutine
(&) etc. The syntax also allows a name that consists of a single non-alphanumeric character after the
initial special character, eg. $$, $?; such names are usually reserved for the Perl system.
If we write an assignment, eg. j=j+1, the occurrence of j on the left denotes a storage location, while
the right-hand occurrence denotes the contents of the storage location. We sometimes refer to these
as the L-value and R-value 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 occurrences 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.

3.2.2 PERL – Variables and its Types


The reserved memory locations to store values are the Variables. This means that creating a variable,
reserves a space in memory. Data type of a variable helps the interpreter to allocate memory and
decide what to be stored in the reserved memory. Therefore, variables can store integers, decimals, or
strings with the assignment of different data types to the variables.
Perl has the following three basic data types namely –
i. Scalars
ii. Arrays
iii. Hashes
Hence, three types of variables will be used in Perl.

 A scalar variable can store either a number, a string, or a reference and will precede by a
dollar sign ($).

 An array variable will store ordered lists of scalars and precede by @ sign.

 The Hash variable will be used to store sets of key/value pairs and will precede by sign %.

 Creating Variables

Perl variables need not to be declared explicitly to reserve memory space. Just like other
programming languages, the operand to the left of the ‘=’ operator is basically the name of the
variable, and the operand to the right of the ‘=’ operator is basically the value stored in the variable.
For example:
$age = 30;
$name = “Mounika”;
$salary = 40000;

Here 30, “Mounika” and 40000 are the values assigned to $age, $name and $salary variables,
respectively.

i. Scalar Variables
A scalar is a single unit of data. It is possible that the data might be an integer number, floating
point, a character, a string, a paragraph, or an entire web page. Here is an example of using scalar
variables

Output:

Age = 30

Name = Mounika

Salary = 40000

ii. Array Variables


Variable that stores an ordered list of scalar values is of array type. Variables of Array Data type
are preceded by an “at” (@) sign. The dollar sign ($) is used to refer a single element of an array
with the variable name followed by the index of the element in square brackets.
Here is an example of how to use an array variable:

Here we used ‘\’ before the ‘$’ sign just to print it as a statement. Otherwise Perl will by default
understand it as a variable and will print the value stored in it. When executed, following result
will be produced –
Output:

$ages[0] = 20

$ages[1] = 25

$ages[2] = 30

$names[0] = Grithika

$names[1] = Haritha

$names[2] = Mounika

iii. Hash Variables


A hash is a set of key/value pairs. Variables of the Hash type are preceded by a modulus (%) sign.
Keys are used to refer to a single variable in the Hash. To access these elements, Hash variable
name followed by the Key associated with the value is used in curly brackets.
Following is a simple example to show Hash Variable:

Output:

$data{'Grithika'} = 20

$data{'Harika'} = 25

$data{'Mounika'} = 30

 Variable Context
Based on the Context, Perl treats the same variable differently i.e., situation where a variable is
being used.

Example:
Output:

Given names are :GrithikaHarikaMounika

Number of names are : 3

Here @names is an array, which has been used in two different contexts. First, we copied it into
any other array, i.e., list, so it returned all the elements assuming that context is list context. Next,
the same array is tried to be stored in a scalar, which further returned just the number of elements
in this array by default assuming it to be a scalar context. Following table displays the various
contexts:

S no. Context & Description

Scalar
1. Assignment to a scalar variable evaluates the value on the right of ‘=’ in a scalar context.
S no. Context & Description

List
2. Assignment to an array or a hash evaluates the right of ‘=’ in a list context.

Boolean
A boolean context is simply a place where expression is evaluated just to check whether it
3.
is true or false.

Void
4. This context doesn’t care what the return value is, even it doesn’t want a return value.

Interpolative
This context will only arise inside the quotes (“”), or with things that behave like
5.
quotes(“”).

3.2.3 Scalar Expressions

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.

Here is a simple example of using scalar variables –


 Numeric Scalars

A scalar is most often either a number or a string. Following example demonstrates the usage of
various types of numeric scalars –
 String Scalars

Following example demonstrates the usage of various types of string scalars. Notice the difference
between single quoted strings and double quoted strings –
 Scalar Operations

You will see a detail of various operators available in Perl in a separate chapter, but here we are
going to list down few numeric and string operations.
 Multiline Strings

If you want to introduce multiline strings into your programs, you can use the standard single quotes
as below –

You can use "here" document syntax as well to store or print multilines as below –
 V-Strings

A literal of the form v1.20.300.4000 is parsed as a string composed of characters with the specified
ordinals. This form is known as v-strings.

A v-string provides an alternative and more readable way to construct strings, rather than use the
somewhat less readable interpolation form "\x{1}\x{14}\x{12c}\x{fa0}".

They are any literal that begins with a v and is followed by one or more dot-separated elements. For
example –
 Special Literals

So far you must have a feeling about string scalars and its concatenation and interpolation opration.
So let me tell you about three special literals __FILE__, __LINE__, and __PACKAGE__ represent
the current filename, line number, and package name at that point in your program.

They may be used only as separate tokens and will not be interpolated into strings. Check the below
example –
3.2.4 Control Structures
Control structures / Control statements enable a programmer to determine the order in which program
statements are executed. These control structures allow you to do two things: 1) skip some statements
while executing others, and 2) repeat one or more statements while some condition is true.
 Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)
 Loops (for, foreach, while, do…while, until, Nested loops)
 Tranfer/Jumping(goto statement)

 Decision Making Statements in Perl :


Decision Making in programming is similar to decision making in real life. In programming, a
certain block of code needs to be executed when some condition is fulfilled. A programming
language uses control statements to control the flow of execution of the program based on certain
conditions. These are used to cause the flow of execution to advance and branch based on changes
to the state of a program.
 If

 If – else

 Nested – If

 if – elsif ladder

 Unless

 Unless – else

 Unless – elsif

 if statement
The if statement is same as in other programming languages. It is used to perform basic condition
based task. It is used to decide whether a certain statement or block of statements will be executed
or not i.e if a certain condition is true then a block of statement is executed otherwise not.
Syntax :
if(condition)

# code to be executed

Note : If the curly brackets { } are not used with if statements then there will be compile time
error. So it is must to use the brackets { } with if statement.
Flowchart:

Example :
 if – else Statement
The if statement evaluates the code if the condition is true but what if the condition is not true, here
comes the else statement. It tells the code what to do when the if condition is false.
Syntax :
if(condition)

# code if condition is true

else

# code if condition is false

Flowchart:
Example :
 Nested – if Statement
if statement inside an if statement is known as nested if. if statement in this case is the target of
another if or else statement. When more than one condition needs to be true and one of the
condition is the sub-condition of parent condition, nested if can be used.
Syntax :
if (condition1)

# Executes when condition1 is true

if (condition2)

# Executes when condition2 is true

Flowchart :

Example :
 If – elsif – else ladder Statement
Here, a user can decide among multiple options. The if statements are executed from the top down.
As soon as one of the conditions controlling the if is true, the statement associated with that get
executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else
statement will be executed.
Syntax :
if(condition1)

# code to be executed if condition1 is true

elsif(condition2)

{
# code to be executed if condition2 is true

elsif(condition3)

# code to be executed if condition3 is true

...

else

# code to be executed if all the conditions are false

Flowchart:

Example :
 unless Statement
In this case if the condition is false then the statements will execute. The number 0, the empty
string “”, character ‘0’, the empty list (), and undef are all false in a boolean context and all
other values are true.
Syntax :
unless(boolean_expression)

{
# will execute if the given condition is false

Flowchart:

Example :
 Unless-else Statement
Unless statement can be followed by an optional else statement, which executes when the boolean
expression is true.
Syntax :
unless(boolean_expression)

# execute if the given condition is false

else

# execute if the given condition is true

Flowchart:

Example :
 Unless – elsif Statement
Unless statement can be followed by an optional elsif…else statement, which is very useful to test
the various conditions using single unless…elsif statement.
Points to Remember :
 Unless statement can have zero to many elsif’s and all that must come before the else.
 Unless statement can have zero or one else’s and that must come after any elsif’s.
 Once an elsif succeeds, then none of remaining elsif’s or else’s will be tested.
Syntax :
unless(boolean_expression 1)

{
# Executes when the boolean expression 1 is false

elsif( boolean_expression 2)

# Executes when the boolean expression 2 is true

else

# Executes when the none of the above condition is met

Flowchart:

Example :
 Looping Statements in Perl :

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

Flow Chart:

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.
Example :
Output:
HiStudents
HiStudents
HiStudents

 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

FlowChart:
Example:

Output:
HiEveryOne

 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

FlowChart:

Example :
Output:
HelloAll
HelloAll
HelloAll
HelloAll

 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);

FlowChart:

Example :
 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

FlowChart:
Example :
 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 :
 Transfer/Jumping Statement in Perl:
The goto statement in Perl is a jump statement which is sometimes also referred to as
unconditional jump statement. The goto statement can be used to jump from anywhere to
anywhere within a function.
Syntax:
LABEL:
Statement 1;
Statement 2;
.
.
.
Statement n;
goto LABEL;
In the above syntax, the goto statement will instruct the compiler to immediately go/jump to the
statement marked as LABEL. Here label is a user-defined identifier which indicates the target
statement. The statement immediately followed after ‘label:’ is the destination statement.

Flowchart:

goto statement in Perl is of three forms- Label, Expression, and Subroutine.


1. Label: It will simply jump to the statement marked with the LABEL, and will continue the
execution from that statement.
2. Expression: In this form, there will be an expression that will return a Label name after
evaluation and goto will make it jump to the labeled statement.
3. Subroutine: goto will transfer the compiler to the subroutine of the given name from the
currently running subroutine.
Syntax:
goto LABEL

goto EXPRESSION

goto Subroutine_Name
goto using LABEL name: LABEL name is used to jump to a specific statement in code and will
start execution from that statement. Its reach is limited though. It can work only within the scope
from where it is being called.
Example:

Output:
1 2 3 4 5 6 7 8 9 10

goto using Expression: An expression can also be used to give a call to a specific label and pass
the execution control to that label. This expression when passed to the goto statement, evaluates
to generate a label name, and further execution is continued from that statement defined by that
label name.
Example:
goto using Subroutine: A subroutine can also be called with the use of the goto statement. This
subroutine is called from within another subroutine or individually based on its use. It holds the
work that is to be performed next to the calling statement. This method can be used to call a
function recursively to print a series or a range of characters.
Example:
3.2.5 Arrays
In Perl, array is a special type of variable. The array is used to store the list of values and each object
of the list is termed as an element. Elements can either be a number, string, or any type of scalar data
including another variable.

Example:
@number = (50, 70, 46);

@names = ("Geeks", "For", "Geeks");

 Array Creation: In Perl programming every array variable is declared using “@” sign before the
variable’s name. A single array can also store elements of multiple datatypes. For Example:
# Define an array

@arr = (1, 2, 3);

@arr = (1, 2, 3, "Hello");

 Array creation using qw function:


qw() function is the easiest way to create an array of single-quoted words. It takes an expression as
an input and extracts the words separated by a whitespace and then returns a list of those words. The
best thing is that the expression can be surrounded by any delimiter like- () ” [] {} // etc. However ()
and // are used generally.
Syntax:
qw (Expression)

qw /Expression/

qw 'Expression'

qw {Expression}

Example :
Output:
Elements of arr1 are:
This
is
a
Perl
Notes
Elements of arr2 are:
a
Perl
Notes

 Accessing Array Elements: For accessing the elements of an array we must prefix “$” sign
before the array variable name followed by the index in square brackets. For Example:
# Define an array

@arr = (1, 2, 3);

# Accessing and printing first

# element of an array

print "$arr[0]\n";

# Accessing and printing second

# element of an array

print "$arr[1]\n";

Example:

Note: Array indices always start from zero. To access the first element it must to give 0 as
indices. We can also give a negative index. But giving negative index will result in selecting the
array elements from ending not from the beginning.
Example:
 Sequential Number Arrays: Perl also provides a shortcut to make a sequential array of numbers
or letters. It makes out the user’s task easy. Using sequential number arrays users can skip out
loops and typing each element when counting to 1000 or letters A to Z etc.
 @array = (1..9); # array with numbers from 1 to 9
 @array = (a..h); # array with letters from a to h
Example:
 Size of an Array: The size of an array(physical size of the array) can be found by evaluating the
array in scalar context. The returned value will be the number of elements in the array. An array
can be evaluated in scalar context using two ways:
1. Implicit Scalar Context
$size = @array;

2. Explicit scalar context using keyword scalar


$size = scalar @array;

Both ways will produce the same output so it is preferred to use an implicit scalar context.

Example:

Note: In Perl arrays, the size of an array is always equal to (maximum_index + 1) i.e.
size = maximum_index + 1

And you can find the maximum index of array by using $#array. So @array and scalar @array is
always used to find the size of an array.
Example:
 Iterating through an Array: We can iterate in an array using two ways:
 Iterating through the range: We can iterate through the range by finding the size of an array
and then running a for loop from 0 to the size – 1 and then accessing the elements of the array.
Example:
 Iterating through elements(foreach Loop): We can iterate through the elements using foreach

loop. Using this we can directly access the elements of the array using a loop instead of running a
loop over its range and then accessing the elements.
Example:
 Array Slices:
In Perl, array is a special type of variable. The array is used to store the list of values and each
object of the list is termed as an element. Elements can either be a number, string, or any typ e of
scalar data including another variable.
Arrays can store any type of data and that data can be accessed in multiple ways. These values can
be extracted by placing $ sign before the array and storing the index value of the element to be
accessed within the square brackets.
For Example:

This method of extracting array elements can be used only to extract one element at a time, which
might become confusing when there is a long list of elements to be accessed. For Example, if the
list contains 100 elements and we need to extract 20 elements from Index ‘a’ to Index ‘b’, then
this method will create a confusion. In order to avoid such kind of situation, Perl provides a
method of array slicing. This can be used to access a range of array elements.

 Slicing of an Array

Array slicing is done to access a range of elements in an array in order to ease the process of
accessing a multiple number of elements from the array. This can be done in two ways:

 Passing multiple index values


 Using range operator
Passing multiple Index values:
Array slicing can be done by passing multiple index values from the array whose values are to be
accessed. These values are passed to the array name as the argument. Perl will access these values
on the specified indices and perform the required action on these values.
Example:
Extracted elements: for all

This method of passing multiple indexes becomes a bit complicated when a large number of
values are to be accessed.

Using Range Operator


Range operator[..] can also be used to perform the slicing method in an array by accessing a range
of elements whose starting and ending index are given within the square brackets separated by
range operator(..). This method is more feasible as it can print elements within a long range of
elements, as compared to passing multiple parameters.
Example:

Output:
Extracted elements: for all students

This method of slicing the Array to access elements is used widely to perform multiple operations
on the array. Operations like, pushing elements, printing elements of array, deleting elements, etc.

 Arrays (push, pop, shift, unshift)

Perl provides various inbuilt functions to add and remove the elements in an array.

Function Description

push Inserts values of the list at the end of an array

pop Removes the last value of an array

shift Shifts all the values of an array on its left

unshift Adds the list element to the front of an array

 push function
This function inserts the values given in the list at an end of an array. Multiple values can be
inserted separated by comma. This function increases the size of an array. It returns number of
elements in new array.

Syntax: push(Array, list)

Example:
Output:

Original array: Java C C++


Updated array: Java C C++ Python Perl

 pop function
This function is used to remove the last element of the array. After executing the pop function,
size of the array is decremented by one element. This function returns undef if list is empty
otherwise returns the last element of the array.
Syntax: pop(Array)

Example:

 shift function
This function returns the first value in an array, removing it and shifting the elements of the array
list to the left by one. Shift operation removes the value like pop but is taken from the start of the
array instead of the end as in pop. This function returns undef if the array is empty otherwise
returns first element of the array.
Syntax: shift(Array)

Example:

 unshift function
This function places the given list of elements at the beginning of an array. Thereby shifting all
the values in an array by right. Multiple values can be unshift using this operation. This function
returns the number of new elements in an array.

Syntax: unshift(Array, List)

Example:
3.2.6 Lists
A list is a collection of scalar values. We can access the elements of a list using indexes. Index starts
with 0 (0th index refers to the first element of the list). We use parenthesis and comma operators to
construct a list. In Perl, scalar variables start with a $ symbol whereas list variables start with @
symbol.
Important Note : List in perl is not a data structure. They are only some subexpressions/expressions
in code. They are typically assigned to an array.
Lists are of multiple types as described below:

 Simple Lists: A list with same datatypes is referred to as a Simple List


Example :

Output:

Empty list:
Integer list: 1 2 3
String list: Hi for all

 Complex Lists: A list may contain various different datatypes. These type of lists are referred
to as Complex Lists.
Example :

Output:

Complex List: 1 2 Hi for all

 Flattening List: A list may contain another list within it but Perl will flatten the internal list
and the elements of this list will be treated as the elements of the outer list.
Example :

Output:

Printing list within list: 1 Hi 3 For 5 6 7


 Accessing List Elements
List elements can be accessed with the use of a scalar variable. While accessing a List element, $
is used, because a scalar variable in Perl is accessed with the use of $ symbol.
Example :

 Slicing a List
Slicing a list in Perl can be done by giving comma(,) separated index values to another list.
Example:
Output:

Sliced List: Hi 3 5

 Defining Range in a List


Range operator in Perl is used as a short way to create a list. When used with list, the range
operator simplifies the process of creating a list with contiguous sequences of numbers and letters.
The range operator can also be used for slicing the list.

Syntax: leftValue..rightValue

Note: If leftValue is greater than rightValue then it will create an empty list otherwise it will
contiguously allocate values from leftValue till rightValue.

Examples :

 Combining Ranges and Slices:

Range and slice operators can be combined together to perform slicing operation on a list.
Example:
3.2.7 Hashes
A hash is a set of key-value pairs. Perl stores elements of a hash such that it searches for the
values based on its keys. Hash variables start with a ‘%’ sign.
Perl requires the keys of a hash to be strings, whereas the values can be any scalars. These values
can either be a number, string or reference. If non-string values are used as the keys, it gives an
unexpected result.
A hash key must be unique. If a new key-value pair is added to a hash and that key is existing
then its corresponding value is overwritten.

 Creating Hashes

There are many ways to initialize a hash variable which are shown below:

 The value is directly assigned as shown below and data is added to an existing hash.
$stud{'Comp'} = 45;
$stud{'Inft'} = 42;

$stud{'Extc'} = 35;

 Another way is by using list which gets converted to hash by taking individual pairs. The first
element of the pair is used as the key, and the second is taken as the value.
%stud = ('Comp', 45, 'Inft', 42, 'Extc', 35);

 One way is using => to indicate the key/value pairs as shown below :
%stud = ('Comp' => 45, 'Inft' => 42, 'Extc' => 35);

 Another way of doing the same thing is as shown below. Here all the keys are preceded by
hyphen (-) and so no quotation is required around them. Hash can be build using this method
only if there are no spaces in the word.
%stud = (-Comp => 45, -Inft => 42, -Extc => 35);

 Accessing Hash Elements

To access the individual element from the hash, variable is prefixed with a dollar sign ($) and then
append the element key within curly braces after the name of the variable.

The below Example illustrates all of the methods of Hash creation as explained above:

Example :
 Extracting Keys and Values
Sometimes there is a need to extract keys and values of a hash to perform various operations on it.
Operations like element modification, deletion, addition, etc. Hash allows to extract these keys
and values with the use of inbuilt functions.
Getting a list of all of the keys from a hash can be done using keys function.
Syntax: keys %HASH

Returns an array of all the keys present in the HASH

Example:

Similarly, values function is used to get a list of all the values.


Syntax: values %HASH
Returns an array with all the values of HASH
Example:
 Hash Operations
As most readers likely know, the hash stores data by using a mechanism called Hashing. In
hashing, a key is used to determine a value or data. These keys must be unique and are then used
as the index at which the data associated with the key is stored. This data does not have to be
unique. It may be duplicated.
Hash is a data structure that stores data by maintaining relations between keys and values
or key/value pairs. Given a key, we can find its value. Key/value pairs are mutable objects and
hence, they can be changed whenever you want to. The key in a hash can be further defined as an
object that is used to retrieve a value. The main advantage of using a hash over arrays is that hash
allows the execution time of basic operations like, to get a value or to set a value at a particular
key (index in case of arrays), to remain constant even for large data sets.
Note that hashes in Perl are not ordered. This means that when you iterate over a hash, you may
not extract the values in the same order in which they were inserted.
The values stored in a hash can of type integer, float, string, boolean, arrays and hash itself.
Here, the data type at key Traffic is hash and at key AllVehicles is of type array. So, the output is the
address of the first element of the hash and array respectively.
 Operations on Hash
Perl hash operations include various operations which are acted upon hash to store and retrieve
data more efficiently. The most commonly used operations in the hash are :

1. Accessing the keys and values in a hash.


2. Modifying the values of particular keys.
3. Loop over to the hash.
Each operation in Perl Hash is explained below with examples:

 Look up/Accessing Perl hash values or keys


Looking up or accessing means to able to access each and every key/value pair of a hash for
further manipulation. Keys in Perl store elements of a Hash in such an optimal way that its values
can be fetched very fast. Values in a hash can be looked up using respective key name embedded
in between {} brackets.
Syntax : $hash_name{key_name};

Example:

 Modify hash elements


Values in a hash are not fixed, that is they are prone to change and Perl provide this ability to
modify and update the values in a hash. For a given key, to modify or update its corresponding
value use following syntax :
Syntax : $hash{‘Key’} = modified_value;
To Modify a given key without changing its corresponding value, simply create an additional key
which is the modified key and assign value (for which you want this new key) to this key and then
delete the previous key/value pair using delete keyword.
Example :
 Loop over Perl hash values
Perl allows to Loop over its Hash values. It means the hash is iterative type and one can iterate
over its keys and values using ‘for’ loop and ‘while’ loop. In Perl, hash data structure is provided
by the keys() function similar to the one present in Python programming language. This keys()
function allows you to get a list of keys of the hash in scalars which can be further used to iterate
over the values of respective keys of the hash.

Syntax keys %Hash

Besides, Perl provides two ways to loop over all the elements in a hash.

1. Perl foreach loop


2. Perl while loop with each function
In the above example, the code gives address of the first element of the array and the hash stored
at key ‘AllVehicles’ and ‘Traffic’ respectively. To overcome this, we have to loop over inside the
array and hash also.
3.2.8 Strings
A string in Perl is a scalar variable and start with a ($) sign and it can contain alphabets, numbers,
special characters. The string can consist of a single word, a group of words or a multi-line
paragraph. The String is defined by the user within a single quote (‘) or double quote (“).

 Quoted Strings: In Perl, strings can be put in between double-quotes (” “) or in between single-
quotes (‘ ‘). However, strings defined in single-quotes and those defined in double-quotes are
treated differently.
 Double-quoted strings: Double-quoted strings are interpolated i.e. variable names (scalars, arrays,
and hashes) are replaced by their original values and escape sequences (like /t, /n, etc.) do their
work. qq operator can also be used in place of double-quoted strings.
 Single-quoted strings: Single-quoted strings are not interpolated. They are interpreted as is, with
no modifications whatsoever. q operator in Perl provides the same use as the single-quoted string.

Example:
Interpolation of Strings with the use of double quotes can sometimes become tricky because some
strings contain symbols which might be of no use when interpolated. For example: ‘@’ symbol used in
writing email addresses.
When an email address is to be stored in a double-quoted string, then the ‘at’ (@) sign is automatically
interpolated and is taken to be the beginning of the name of an array and is substituted by it. If an array
with that name is found then it will replace the array name with the array values, or it will be left blank
if an array with that name doesn’t exist.
Example:

Output:
[email protected]
In the above example, the string ($email) is interpolated and @gmail is substituted by an array named
‘@gmail’ but since no array with such name is found, @gmail is removed but is not substituted and
hence “abcdefghijklmnopqrstuvwxyz.com” is printed. In the below example, @gmail has been pre-
defined and hence is substituted in place of @gmail.
Example:

Output:
abcdefghijklmnopqrstuvwxyza b c d e f g .com
This can be corrected by using single quotes in place of double quotes. Assigning the string to the
variable with the use of single quotes will remove the interpolation and hence the ‘@’ will not be
considered as array declaration.
Example:

Output:
[email protected]
Above solution to the interpolation problem contains a drawback. What if there’s a need to substitute a
variable’s value in the string along with the use of ‘@’ symbol. Then this method will be of no use as
single quotes won’t allow the substitution of variable’s value. To overcome this situation, the escape
character i.e. the backslash(\) is used. The backslash is inserted just before the ‘@’ as shown below:

Output:
[email protected]
[email protected]

 Escaping the escape character

The backslash is the escape character and is used to make use of escape sequences. When there is a
need to insert the escape character in an interpolated string, the same backslash is used, to escape the
substitution of escape character with ” (blank). This allows the use of escape character in the
interpolated string.

Example:
 Escaping double quotes

Use of double quotes in a string signifies the end of the string and hence, cannot be inserted
directly. To insert double quotes in an interpolated string, backslash is used just before the double
quotes to escape its interpolation.
Example:

Output:
This page is "Hello my dear students".

 String Operators
Operators are the foundation of any programming language. Thus, the functionality of Perl
programming language is incomplete without the use of operators. A user can define operators as
symbols that help to perform specific mathematical and logical computations on operands. String
are scalar variables and start with ($) sign in Perl. The String is defined by user within a single
quote (‘) or double quote (“) . There are different types of string operators in Perl, as follows:

 Concatenation Operator (.)


 Repetition Operator (x)

 Concatenation Operator(.)

Perl strings are concatenated with a Dot(.) symbol. The Dot(.) sign is used instead of (+) sign in
Perl. This operator takes two scalars variables as operands and combines them in a single scalar
variable. Both scalars i.e left and right will convert into a single string.
Example:

Output:
String After Concatenation = HelloEveryone

 Repetition Operator (x)


The x operator accepts a string on its left-hand side and a number on its right-hand side. It will
return the string on the left-hand side repeated as many times as the value on the right-hand side.
The repetition depends on the user’s input number.
Syntax:

"String" x number_of_times

Example:

Output:
HelloEveryone HelloEveryone HelloEveryone HelloEveryone HelloEveryone
Note: Possible cases while using the Repetition Operator (x) in String as follows:

 $string xnumber : Gives Output


 $string x number : Gives Output
 $stringxnumber : Gives Error(where no space between string and x)
 $stringx number : Gives Error(where no space between string and x)

Important Point to Remember: Both the Concatenation and Repetition operator can be used with
assignment(=) operator as follows:
 Concatenation Assignment Operator (.=)
 Repetition Assignment Operator (x=)
Example:

Output:
HelloEveryone
Over_hereOver_hereOver_hereOver_hereOver_here
3.2.9 Pattern and Regular Expressions
Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a
search pattern within a given text. Regex in Perl is linked to the host language and is not the same
as in PHP, Python, etc. Sometimes it is termed as “Perl 5 Compatible Regular Expressions“. To
use the Regex, Binding operators like ‘=~‘(Regex Operator) and ‘!~‘ (Negated Regex Operator)
are used. Before moving to Binding operators let’s have a look at building patterns.
Building Patterns: In Perl, patterns can be constructed using the m// operator. In this operator, the
required pattern is simply placed between the two slashes and the binding operators are used to
search for the pattern in the specified string.

A regular expression is a string of characters that defines the pattern or patterns you are viewing. The
syntax of regular expressions in Perl is very similar to what you will find within other regular

expression.supporting programs, such as sed, grep, and awk.

The basic method for applying a regular expression is to use the pattern binding operators =~ and !~.
The first operator is a test and assignment operator.

There are three regular expression operators within Perl.

 Match Regular Expression - m//


 Substitute Regular Expression - s///
 Transliterate Regular Expression - tr///

The forward slashes in each case act as delimiters for the regular expression (regex) that you are
specifying. If you are comfortable with any other delimiter, then you can use in place of forward
slash.

 The Match Operator

The match operator, m//, is used to match a string or statement to a regular expression. For example,
to match the character sequence "foo" against the scalar $bar, you might use a statement like this –
 Match Operator Modifiers

The match operator supports its own set of modifiers. The /g modifier allows for global matching.
The /i modifier will make the match case insensitive. Here is the complete list of modifiers

Sr.No. Modifier & Description

1 i
Makes the match case insensitive.

m
2
Specifies that if the string has newline or carriage return characters, the ^ and $ operators
will now match against a newline boundary, instead of a string boundary.

3 o
Evaluates the expression only once.

4 s
Allows use of . to match a newline character.
5 x
Allows you to use white space in the expression for clarity.

6 g
Globally finds all matches.

7 cg
Allows the search to continue even after a global match fails.

 The Substitution Operator

The substitution operator, s///, is really just an extension of the match operator that allows you to
replace the text matched with some new text. The basic form of the operator is −

The PATTERN is the regular expression for the text that we are looking for. The REPLACEMENT
is a specification for the text or regular expression that we want to use to replace the found text with.
For example, we can replace all occurrences of dog with cat using the following regular expression –
 Substitution Operator Modifiers

Here is the list of all the modifiers used with substitution operator.

Sr.No. Modifier & Description

1 i
Makes the match case insensitive.

m
2
Specifies that if the string has newline or carriage return characters, the ^ and $
operators will now match against a newline boundary, instead of a string boundary.

3 o
Evaluates the expression only once.

4 s
Allows use of . to match a newline character.

5 x
Allows you to use white space in the expression for clarity.

6 g
Replaces all occurrences of the found expression with the replacement text.

e
7
Evaluates the replacement as if it were a Perl statement, and uses its return value as the
replacement text.

 The Translation Operator

Translation is similar, but not identical, to the principles of substitution, but unlike substitution,
translation (or transliteration) does not use regular expressions for its search on replacement values.
The translation operators are −
The translation replaces all occurrences of the characters in SEARCHLIST with the corresponding
characters in REPLACEMENTLIST. For example, using the "The cat sat on the mat." string we have
been using here –

Standard Perl ranges can also be used, allowing you to specify ranges of characters either by letter or
numerical value. To change the case of the string, you might use the following syntax in place of
the uc function.

 Translation Operator Modifiers

Following is the list of operators related to translation.

Sr.No. Modifier & Description

1 c
Complements SEARCHLIST.

2 d
Deletes found but unreplaced characters.

3 s
Squashes duplicate replaced characters.
3.2.10 Subroutines

A Perl subroutine or function is a group of statements that together performs a task. You can divide
up your code into separate subroutines. How you divide up your code among different subroutines is
up to you, but logically the division usually is so each function performs a specific task.

Perl uses the terms subroutine, method and function interchangeably.

 Define and Call a Subroutine

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

The typical way of calling that Perl subroutine is as follows −

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.

 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 –
 Passing Lists to Subroutines

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 –
 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 –
 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 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 –
 Private Variables in a Subroutine

By default, all variables in Perl are global variables, which means they can be accessed from
anywhere in the program. But you can create private variables called lexical variables at any time
with the my operator.

The my operator confines a variable to a particular region of code in which it can be used and
accessed. Outside that region, this variable cannot be used or accessed. This region is called its
scope. 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 −

Let's check the following example to distinguish between global and private variables –
 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 –

($sec,$min,$hour,$mday,$mon, $year,$wday,$yday,$isdst) =
localtime(time);

Now the individual variables contain the corresponding values returned by localtime() subroutine.

You might also like