Mastering Perl: A Beginner's Guide 103241510X, 9781032415109

Mastering Perl helps readers to learn the Perl programming language with real-world examples. High-level, interpreted, a

276 128 7MB

English Pages 311 [313] Year 2023

Report DMCA / Copyright

DOWNLOAD FILE

Polecaj historie

Mastering Perl: A Beginner's Guide
 103241510X, 9781032415109

Table of contents :
Cover
Half Title
Series Page
Title Page
Copyright Page
Dedication
Contents
About the Editor
Acknowledgments
Zeba Academy – Mastering Computer Science
CHAPTER 1: Introduction
EVOLUTION OF PERL
WHY PERL?
PERL FEATURES
PERL APPLICATION
PERL IMPLEMENTATION
PROGRAMMING IN PERL
Comments
Perl’s Benefits
Perl’s Disadvantages
Applications
PERL INSTALLATION AND CONFIGURATION ON WINDOWS, LINUX, AND MACOS
PERL DOWNLOAD AND INSTALLATION
HELLO WORLD PROGRAM
HOW TO EXECUTE A PERL PROGRAM
Windows
Unix/Linux
A PERL PROGRAM’S BASIC SYNTAX
Variables
Expressions
Comments
Statements
Block
Functions or Subroutines
Loops
Whitespaces and Indentation
Keywords
DATA TYPES
Scalars
Arrays
Hashes
NOTE
CHAPTER 2: Fundamentals of Perl
PERL CODE WRITING METHODS
Interactive Mode
Script Mode
One-Liner Mode
BOOLEAN VALUES IN PERL
OPERATORS
Arithmetic Operators
Addition
Subtraction
Multiplication
Division
Modulus
Exponent Operator
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Ternary Operator
VARIABLES IN PERL
Naming of a Variable
Declaration of a Variable
Modification of a Variable
Variable Interpolation
VARIABLES AND ITS TYPES
Creating Variables
Scalar Variables
Array Variables
Hash Variables
Variable Context
SCOPE OF VARIABLES
The Scope of Global Variables
Lexical Variables’ Scope (Private Variables)
Package Variables
MODULES IN PERL
Making a Perl Module
Importing and Using a Perl Module
Utilizing Module Variables
Making Use of predefined Modules
PERL PACKAGES
Perl Module Declaration
Making Use of a Perl Module
Using a Different Directory to Access a Package
Utilizing Module Variables
Begin and End Block
NUMBER AND ITS TYPES IN PERL
DIRECTORIES WITH CRUD OPERATIONS IN PERL
Making a New Directory
Opening an Existing Directory
Read Directory in the Scalar and List Context
Modifying Directory Path
Directory Closing
Delete a Directory
NOTES
CHAPTER 3: Input and Output in Perl
PERL print() AND say() METHODS
print() Operator
say() Function
print OPERATOR
USE OF STDIN FOR INPUT
CHAPTER 4: Control Flow in Perl
DECISION-MAKING IN PERL
if Statement
if else Statement
Nested if Statement
if elsif else ladder Statement
unless Statement
unless else Statement
unless elsif Statement
LOOPS IN PERL
for Loop
foreach Loop
while Loop
Infinite While Loop
do...while loop
until Loop
Nested Loops
given-when STATEMENT
Nested given-when Statement
goto STATEMENT
next OPERATOR
redo OPERATOR
last IN LOOP
NOTES
CHAPTER 5: File Handling in Perl
INTRODUCTION OF FILE HANDLING
Using FileHandle To Read and Write to a File
Various File Handling Modes
Redirecting Output
FILE OPENING AND READING
Opening a File
Reading a File
FileHandle Operator
getc Function
read Function
Reading More than One Line at a Time
Exception Handling in Files
Throw an Exception
Give a Warning
WRITING TO A FILE
print() Function
Error Handling and Error Reporting
Throw an Exception (Using Die Function)
Give a Warning (Using Warn Function)
APPENDING TO A FILE
CSV FILE READING
Use of Split() for Data Extraction
Character Escaping a Comma
Installation of the TEXT::CSV
Fields with Newlines Embedded
FILE TEST OPERATORS
FILE LOCKING
flock()
flock() vs lockf()
SLURP MODULE
USEFUL FILE-HANDLING FUNCTIONS
CHAPTER 6: Regular Expressions in Perl
OPERATORS IN REGULAR EXPRESSION
REGEX CHARACTER CLASSES
SPECIAL CHARACTER CLASSES IN REGULAR EXPRESSIONS
QUANTIFIERS IN REGULAR EXPRESSION
Quantifier Table
BACKTRACKING IN REGULAR EXPRESSION
BACKTRACKING
“e” MODIFIER IN REGULAR EXPRESSION
The Substitution Operation Is Performed using a Subroutine
REGEX “ee” MODIFIER
When Doing Mathematical Calculations, Use the “ee” Modifier
pos() FUNCTION IN REGULAR EXPRESSION
To Match from a Specified Position, use \G Assertion
REGEX CHEAT SHEET
Character Classes
Anchors
Metacharacters
Quantifiers
Modifiers
White Space Modifiers
Quantifiers – Modifiers
Grouping and Capturing
SEARCHING IN A FILE USING REGEX
Regular Search
Using Word Boundary in the Regex Search
Use of Wildcards in the Regular Expression
CHAPTER 7: Object-Oriented Programming in Perl
CLASSES IN OOP
Object
Class
Data Member
Defining a Class
Creating a Class and Making Use of Objects
Creating a Class Instance
Creating an Object
OBJECTS IN OOPs
METHODS IN OOPs
Types of Methods in Perl
get-set Methods
CONSTRUCTORS AND DESTRUCTORS
Constructors
Passing Dynamic Attributes
Destructors
METHOD OVERRIDING IN OOPs
Why Do We Override Methods?
INHERITANCE IN OOPs
Base Class and Derived Class
Multilevel Inheritance
Implementing Inheritance in the Perl
POLYMORPHISM IN OOPs
ENCAPSULATION IN OOPs
NOTE
CHAPTER 8: Subroutines in Perl
SUBROUTINES OR FUNCTIONS
Determining Subroutines
Calling Subroutines
Passing Parameters to Subroutines
Passing Hashes to Subroutines
Passing Lists to Subroutines
Returning a Value from a Subroutine
Local and Global Variables in Subroutines
A Varying Number of Parameters in a Subroutine Call
FUNCTION SIGNATURE IN PERL
Defining Subroutines
Function Signature
Passing Parameters of a Type other than that Specified in the Signature
Difference in Number of Arguments
PASSING COMPLEX PARAMETERS TO A SUBROUTINE
MUTABLE AND IMMUTABLE PARAMETERS
Mutable Parameters
Immutable Parameters
Traits
MULTIPLE SUBROUTINES
Subroutine Definition
Use of the “multi” Keyword
return() FUNCTION
REFERENCES IN PERL
Making a Reference
Dereferencing
PASS BY REFERENCE
PERL RECURSION
APPRAISAL
BIBLIOGRAPHY
INDEX

Citation preview

Mastering Perl Mastering Perl helps readers to learn the Perl programming language with realworld examples. High-level, interpreted, and multipurpose, Perl’s roots are in text manipulation. It is used for UI development in system administration, networking, and other fields, borrowing heavily from C and Shell scripts. Among programmers, Perl is also known as “Pathologically Eclectic Rubbish Lister” or “Practically Everything Really Likable.” Since Perl’s inception, it has mostly been used for text processing, namely the extraction of data from text files and its subsequent transformation into other formats. In addition to being interoperable with HTML, XML, and other markup languages, Perl provides cross-platform compatibility. It is Open Source, meaning it’s free to use and licensed under both the Artistic and GNU General Public Licenses (GPL). With Mastering Perl, learning Perl becomes a charm and will help readers undoubtedly advance their careers.

About the Series The Mastering Computer Science covers a wide range of topics, spanning programming languages as well as modern-day technologies and frameworks. The series has a special focus on beginner-level content, and is presented in an easy to understand manner, comprising: • Crystal-clear text, spanning various topics sorted by relevance, • Special focus on practical exercises, with numerous code samples and programs, • A guided approach to programming, with step by step tutorials for the absolute beginners, • Keen emphasis on real-world utility of skills, thereby cutting the redundant and seldom-used concepts and focusing instead of industry-prevalent coding paradigm, • A wide range of references and resources, to help both beginner and intermediate-level developers gain the most out of the books. Mastering Computer Science series of books start from the core concepts, and then quickly move on to industry-standard coding practices, to help learners gain efficient and crucial skills in as little time as possible. The books assume no prior knowledge of coding, so even the absolute newbie coders can benefit from this series. Mastering Computer Science series is edited by Sufyan bin Uzayr, a writer and educator with over a decade of experience in the computing field. For more information about this series, please visit: https://www.routledge.com/Mastering-Computer-Science/book-series/MCS

Mastering Perl A Beginner’s Guide

Edited by

Sufyan bin Uzayr

First Edition published 2024 by CRC Press 2385 NW Executive Center Drive, Suite 320, Boca Raton, FL 33431 and by CRC Press 2 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN CRC Press is an imprint of Taylor & Francis Group, LLC © 2024 Sufyan bin Uzayr Reasonable efforts have been made to publish reliable data and information, but the author and publisher cannot assume responsibility for the validity of all materials or the consequences of their use. The authors and publishers have attempted to trace the copyright holders of all material reproduced in this publication and apologize to copyright holders if permission to publish in this form has not been obtained. If any copyright material has not been acknowledged please write and let us know so we may rectify in any future reprint. Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including photocopying, microfilming, and recording, or in any information storage or retrieval system, without written permission from the publishers. For permission to photocopy or use material electronically from this work, access www.copyright.com or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923, 978-750-8400. For works that are not available on CCC please contact mpkbookspermissions@tandf. co.uk Trademark Notice: Product or corporate names may be trademarks or registered trademarks and are used only for identification and explanation without intent to infringe. Library of Congress Cataloging‑in‑Publication Data Names: Bin Uzayr, Sufyan, editor. Title: Mastering Perl : a beginner’s guide / edited by Sufyan bin Uzayr. Description: First edition. | Boca Raton ; London : CRC Press, 2024. | Series: Mastering computer science Identifiers: LCCN 2023007400 (print) | LCCN 2023007401 (ebook) | ISBN 9781032415109 (paperback) | ISBN 9781032415116 (hardback) | ISBN 9781003358442 (ebook) Subjects: LCSH: Perl (Computer program language) | Computer programming. Classification: LCC QA76.73.P47 M37 2024 (print) | LCC QA76.73.P47 (ebook) | DDC 005.13/3--dc23/eng/20230601 LC record available at https://lccn.loc.gov/2023007400 LC ebook record available at https://lccn.loc.gov/2023007401 ISBN: 9781032415116 (hbk) ISBN: 9781032415109 (pbk) ISBN: 9781003358442 (ebk) DOI: 10.1201/9781003358442 Typeset in Minion by KnowledgeWorks Global Ltd.

For Mom

Contents About the Editor, xv Acknowledgments, xvi Zeba Academy – Mastering Computer Science, xvii Chapter 1   ◾    Introduction

1

EVOLUTION OF PERL1 WHY PERL?2 PERL FEATURES3 PERL APPLICATION4 PERL IMPLEMENTATION4 PROGRAMMING IN PERL4 Comments5 Perl’s Benefits6 Perl’s Disadvantages6 Applications6 PERL INSTALLATION AND CONFIGURATION ON WINDOWS, LINUX, AND MACOS7 PERL DOWNLOAD AND INSTALLATION8 HELLO WORLD PROGRAM9 HOW TO EXECUTE A PERL PROGRAM11 Windows11 Unix/Linux11 A PERL PROGRAM’S BASIC SYNTAX11 Variables12 vii

viii   ◾    Contents

Expressions12 Comments13 Statements14 Block14 Functions or Subroutines15 Loops15 Whitespaces and Indentation16 Keywords17 DATA TYPES18 Scalars18 Arrays18 Hashes19 NOTE20

Chapter 2   ◾    Fundamentals of Perl

21

PERL CODE WRITING METHODS21 Interactive Mode22 Script Mode23 One-Liner Mode24 BOOLEAN VALUES IN PERL25 OPERATORS29 Arithmetic Operators30 Addition

30

Subtraction

30

Multiplication

30

Division

30

Modulus

31

Exponent Operator

31

Relational Operators31 Logical Operators34 Bitwise Operators35

Contents   ◾    ix

Assignment Operators37 Ternary Operator40 VARIABLES IN PERL41 Naming of a Variable41 Declaration of a Variable42 Modification of a Variable42 Variable Interpolation43 VARIABLES AND ITS TYPES44 Creating Variables45 Scalar Variables45 Array Variables46 Hash Variables46 Variable Context47 SCOPE OF VARIABLES48 The Scope of Global Variables48 Lexical Variables’ Scope (Private Variables)50 Package Variables52 MODULES IN PERL54 Making a Perl Module54 Importing and Using a Perl Module55 Utilizing Module Variables55 Making Use of predefined Modules56 PERL PACKAGES57 Perl Module Declaration57 Making Use of a Perl Module58 Using a Different Directory to Access a Package58 Utilizing Module Variables59 Begin and End Block60 NUMBER AND ITS TYPES IN PERL60 DIRECTORIES WITH CRUD OPERATIONS IN PERL64 Making a New Directory65 Opening an Existing Directory65

x   ◾    Contents

Read Directory in the Scalar and List Context65 Modifying Directory Path67 Directory Closing68 Delete a Directory68 NOTES69

Chapter 3   ◾    Input and Output in Perl

71

PERL print() AND say() METHODS71 print() Operator71 say() Function73 print OPERATOR73 USE OF STDIN FOR INPUT74

Chapter 4   ◾    Control Flow in Perl

77

DECISION-MAKING IN PERL77 if Statement78 if else Statement79 Nested if Statement81 if elsif else ladder Statement83 unless Statement85 unless else Statement86 unless elsif Statement88 LOOPS IN PERL90 for Loop90 foreach Loop92 while Loop92 Infinite While Loop93 do...while loop93 until Loop94 Nested Loops95 given-when STATEMENT97 Nested given-when Statement98 goto STATEMENT100

Contents   ◾    xi

next OPERATOR103 redo OPERATOR105 last IN LOOP106 NOTES107

Chapter 5   ◾    File Handling in Perl

109

INTRODUCTION OF FILE HANDLING109 Using FileHandle To Read and Write to a File110 Various File Handling Modes111 Redirecting Output115 FILE OPENING AND READING116 Opening a File117 Reading a File117 FileHandle Operator

117

getc Function

118

read Function

118

Reading More than One Line at a Time119 Exception Handling in Files119 Throw an Exception

119

Give a Warning

120

WRITING TO A FILE120 print() Function120 Error Handling and Error Reporting122 Throw an Exception (Using Die Function)

122

Give a Warning (Using Warn Function)

123

APPENDING TO A FILE123 CSV FILE READING125 Use of Split() for Data Extraction125 Character Escaping a Comma127 Installation of the TEXT::CSV128 Fields with Newlines Embedded129 FILE TEST OPERATORS131

xii   ◾    Contents

FILE LOCKING

133

flock()

134

flock() vs lockf()

136

SLURP MODULE

136

USEFUL FILE-HANDLING FUNCTIONS

139

Chapter 6   ◾    Regular Expressions in Perl

141

OPERATORS IN REGULAR EXPRESSION

143

REGEX CHARACTER CLASSES

147

SPECIAL CHARACTER CLASSES IN REGULAR EXPRESSIONS150 QUANTIFIERS IN REGULAR EXPRESSION Quantifier Table

152 153

BACKTRACKING IN REGULAR EXPRESSION

156

BACKTRACKING

158

“e” MODIFIER IN REGULAR EXPRESSION

159

The Substitution Operation Is Performed using a Subroutine REGEX “ee” MODIFIER When Doing Mathematical Calculations, Use the “ee” Modifier pos() FUNCTION IN REGULAR EXPRESSION To Match from a Specified Position, use \G Assertion

160 161 162 164 166

REGEX CHEAT SHEET

167

Character Classes

168

Anchors

169

Metacharacters

170

Quantifiers

170

Modifiers

171

White Space Modifiers

171

Quantifiers – Modifiers

172

Grouping and Capturing

172

SEARCHING IN A FILE USING REGEX Regular Search

172 173

Contents   ◾    xiii

Using Word Boundary in the Regex Search174 Use of Wildcards in the Regular Expression175

Chapter 7   ◾    Object-Oriented Programming in Perl

177

CLASSES IN OOP181 Object181 Class181 Data Member182 Defining a Class182 Creating a Class and Making Use of Objects182 Creating a Class Instance182 Creating an Object183 OBJECTS IN OOPs184 METHODS IN OOPs186 Types of Methods in Perl187 get-set Methods187 CONSTRUCTORS AND DESTRUCTORS189 Constructors189 Passing Dynamic Attributes191 Destructors192 METHOD OVERRIDING IN OOPs192 Why Do We Override Methods?196 INHERITANCE IN OOPs196 Base Class and Derived Class197 Multilevel Inheritance198 Implementing Inheritance in the Perl199 POLYMORPHISM IN OOPs200 ENCAPSULATION IN OOPs203 NOTE205

Chapter 8   ◾    Subroutines in Perl

207

SUBROUTINES OR FUNCTIONS207 Determining Subroutines208

xiv   ◾    Contents

Calling Subroutines208 Passing Parameters to Subroutines208 Passing Hashes to Subroutines210 Passing Lists to Subroutines210 Returning a Value from a Subroutine211 Local and Global Variables in Subroutines212 A Varying Number of Parameters in a Subroutine Call213 FUNCTION SIGNATURE IN PERL214 Defining Subroutines214 Function Signature214 Passing Parameters of a Type other than that Specified in the Signature215 Difference in Number of Arguments216 PASSING COMPLEX PARAMETERS TO A SUBROUTINE217 MUTABLE AND IMMUTABLE PARAMETERS222 Mutable Parameters222 Immutable Parameters222 Traits223 MULTIPLE SUBROUTINES225 Subroutine Definition225 Use of the “multi” Keyword226 return() FUNCTION228 REFERENCES IN PERL229 Making a Reference229 Dereferencing231 PASS BY REFERENCE232 PERL RECURSION234 APPRAISAL, 237 BIBLIOGRAPHY, 281 INDEX, 287

About the Editor Sufyan bin Uzayr is a writer, coder, and entrepreneur having over a decade of experience in the industry. He has authored several books in the past, pertaining to a diverse range of topics, ranging from History to Computers/IT. Sufyan is the Director of Parakozm, a multinational IT company specializing in EdTech solutions. He also runs Zeba Academy, an online learning and teaching vertical with a focus on STEM fields. Sufyan specializes in a wide variety of technologies, such as JavaScript, Dart, WordPress, Drupal, Linux, and Python. He holds multiple degrees, including ones in Management, IT, Literature, and Political Science. Sufyan is a digital nomad, dividing his time between four countries. He has lived and taught in universities and educational institutions around the globe. Sufyan takes a keen interest in technology, politics, literature, history, and sports, and in his spare time, he enjoys teaching coding and English to young students. Learn more at sufyanism.com

xv

Acknowledgments There are many people who deserve being on this page because this book would not have come into existence without their support. That said, some names deserve a special mention, and I am genuinely grateful to: • My parents, for everything they have done for me.    • The Parakozm team, especially Divya Sachdeva, Jaskiran Kaur, and Simran Rao, for offering great amounts of help and assistance during the book-writing process.  • The CRC team, especially Sean Connelly and Danielle Zarfati, for ensuring that the book’s content, layout, formatting, and everything else remains perfect throughout.   • Reviewers of this book, for going through the manuscript and providing their insight and feedback. • Typesetters, cover designers, printers, and everyone else, for their part in the development of this book. • All the folks associated with Zeba Academy, either directly or indirectly, for their help and support. • The programming community, in general, and the web development community in particular, for all their hard work and efforts. Sufyan bin Uzayr

xvi

Zeba Academy – Mastering Computer Science The “Mastering Computer Science” series of books are authored by the Zeba Academy team members, led by Sufyan bin Uzayr, consisting of: • Divya Sachdeva • Jaskiran Kaur • Simran Rao • Aruqqa Khateib • Suleymen Fez • Ibbi Yasmin • Alexander Izbassar Zeba Academy is an EdTech venture that develops courses and content for learners primarily in STEM fields, and offers educational consulting and mentorship to learners and educators worldwide. Additionally, Zeba Academy is actively engaged in running IT Schools in the CIS countries, and is currently working in partnership with numerous universities and institutions. For more info, please visit https://zeba.academy xvii

Chapter

1

Introduction

IN THIS CHAPTER

➢➢ Perl Introduction ➢➢ Installation and Environment Setup ➢➢ Hello World Program Perl is a high-level, interpreted, and dynamic, general-purpose programming language. It was created in 1987 by Larry Wall. Although “Practical Extraction and Reporting Language” is the most common expansion, there is no official full form of Perl. Some programmers refer to Perl as “Pathologically Eclectic Rubbish Lister” and “Practically Everything Likable.” The abbreviation “Practical Extraction and Reporting Language” is often used since Perl was initially designed for text processing, such as extracting the necessary information from a specific text file and converting the text file to a new format. Perl supports both procedural and object-oriented programming. Perl is syntactically similar to C, making it accessible to C and C++ programmers.

EVOLUTION OF PERL It all began when Larry Wall was tasked with generating reports from several text files containing cross-references. Then he began using awk for this work but quickly realized it was insufficient. Instead of designing a tool for this purpose, he created a new programming language, Perl, and its DOI: 10.1201/9781003358442-1

1

2   ◾    Mastering Perl

interpreter. He built the Perl programming language in C, using principles from awk, sed, and LISP, among others. Perl was initially designed only for system administration and text processing, but subsequent versions included the ability to manage regular expressions (Regex) and network sockets. Presently, Perl is renowned for its capability to handle Regex. The first release of Perl was version 1.0 on December 18, 1987. 5.28 is the most recent version of Perl. Perl 6 is distinct from Perl 5 since it is a reimplementation of Perl 5 that is entirely object-oriented.

WHY PERL? Perl’s popularity and demand stem from a variety of factors. Some of the causes are as follows: • Perl is a high-level language; thus, it is similar to other popular programming languages such as C and C++, making it simple for anybody to learn. • Text-processing: As the name “Practical Extraction and Reporting Language” suggests, Perl has powerful text manipulation capabilities, allowing it to create reports from various text files readily. Additionally, it may convert the files to a different format. • Perl incorporates the most exemplary aspects of other languages, such as C, sed, awk, and sh, making the language more useful and productive. • System management: Perl’s ability to use many scripting languages makes system administration a simple operation. Instead of relying on many languages, utilize Perl to fulfill all system management tasks. Despite this, Perl is also used for web development, web automation, and Graphical User Interface (GUI) programming, among other things. • Web and Perl: Perl may be incorporated into web servers to boost their processing capacity, and the DBI module makes web-database interaction quite simple. Getting started with Perl programming: • Locating an interpreter: Numerous online integrated development environments (IDEs) may be used to execute Perl programs without installation.

Introduction   ◾    3

• Windows: A number of IDEs are available to execute Perl applications or scripts, including Padre and Eclipse with the EPIC plugin.

PERL FEATURES • The capabilities listed below are present in Perl and have been widely adopted by other programming and scripting languages. • Most of Perl’s features, including variables, expressions, statements, control structures, and subroutines, are derived from C. • It also utilizes shell scripting tools for detecting data kinds. • Perl provides built-in functions often used in shell programming, such as sort and system facilities use, that may be denoted using leading sigils, such as an array, scalar, and hash. • In addition, Perl 5 supports complicated data structures and an object-oriented programming style that includes packages, references, and compiler directives. • The interpreter knows the storage and memory needs for each data type and allocates and deallocates memory depending on use in all versions of Perl. • It also does typecast during execution, such as converting an integer to a string, and other conversions that are not valid, which result in errors being raised. • Perl does not impose or promote any particular programming style, such as procedural, object-oriented, or functional; the interpreter and its functions constitute the language’s only definition. • Perl has APIs (text manipulation facilities) that help deal with XML, HTML, and other mark-up languages. • Perl offers the most significant level of security and is even certified by Coverity, a third-party security company, for having a low defect density and fewer security issues. • Perl is extensible and includes libraries that handle XML and database integration (DI), such as Oracle and MySQL.

4   ◾    Mastering Perl

PERL APPLICATION Perl, along with Hypertext Preprocessor (PHP) and Python, is a popular programming language among developers. Previously, programmers wrote Common Gateway Interface (CGI) scripts using Perl. Perl is frequently used as a departmental adhesive between heterogeneous and nonseamless interoperable systems. System administrators adore this language because they can enter a single command to accomplish a task that would otherwise require writing a program. Perl is primarily portable, with some Windows and macOS-specific customizations. Additionally, developers use the language to build and deploy. It is used by most suppliers or software manufacturers to package and deploy commercial software (including COTS and bespoke). It is utilized extensively in the fields of finance and bioinformatics due to its capacity to manage and process large data sets.

PERL IMPLEMENTATION As stated before, Perl is an interpreted language written in C with an extensive library of modules written in both C and Perl. The Perl interpreter comprises a massive 150,000 lines of C code, which compiles to 1 MB on most system architectures. There are almost 500 modules in the Perl distribution, including 300,000 lines of Perl code and 200,000 lines of C code. The components of Perl (arrays, scalars, and hashes) are represented as C structures inside the object-oriented design of the interpreter. The interpreter’s life cycle consists of two phases: compilation and execution. The interpreter parses the Perl code into a syntax tree at build time. It executes the Perl program by traversing the tree at runtime. The Perl programming language is offered as open source with 120,000 functional tests; the interpreter and other functional modules are rigorously tested during the compilation process. If these 120K functional tests pass, it is safe to assume that your code will not damage the interpreter.

PROGRAMMING IN PERL Perl is syntactically similar to other commonly known programming languages, making it easy to write and understand. Perl programs can be written in any of the most popular text editors, including Notepad++ and gedit. After creating the program, save the file with the .pl or .PL extension. Type Perl file name.pl on the command line to execute the program.

Introduction   ◾    5

Example: A simple application to print Welcome to PFP! # Program to print Welcome to PFP! #!/usr/bin/perl # Below line will print "Welcome to PFP!" print "Welcome to GFG!\n";

Comments Comments are used to improve code readability. The comment items are ignored by the interpreter and are not executed. Comments might be single or multiple lines. • Single line Comment Syntax: # Single-line-comment

• Multi-line comment Syntax: = Multi-line comments Line start from = is interpreted as starting of multiline comment and =cut is consider as the end of the multiline comment =cut

In the above example: 1. print: It is a Perl function that displays the result or any provided output on the console. 2. Quotes: In Perl, we can use either single or double quotes (‘’ or “”). Single quotes do not interpolate any variable or special character, but double quotes do. 3. \n: It is used for newline character, which escapes any character with a backslash (\). 4. /usr/bin/Perl: It is the original Perl interpreter binary, which always begins with #!. This is used in Perl Script Mode Programming.

6   ◾    Mastering Perl

5. Because Perl is a case-sensitive computer language, $Geeks and $geeks are distinct identifiers. Perl’s Benefits • Perl supports cross-platform compatibility and mark-up languages such as HTML, XML, and others. • It is particularly efficient in text manipulation, i.e. Regex. It also has socket capabilities. • Free and open-source software is released under the Artistic and GNU General Public Licenses (GPL). • Because it is an embeddable language, it can be used in web servers and database servers. • It supports around 25.000 open-source modules on CPAN (Comprehensive Perl Archive Network), which provide numerous useful enhancements to the standard library. For example, XML processing, GUI, and DI, among others. Perl’s Disadvantages • Because of CPAN modules, Perl does not support portability. • Programs run slowly and must be interpreted each time changes are made. • In Perl, the same result may be obtained in a variety of methods, making the code messy and illegible. • When compared to other languages, the usability factor is lower. Applications • Text file processing and string analysis are key uses of the Perl language. • Perl is also used for CGI scripts. • Used in web development and GUI design. • The text-handling features of Perl are also employed to generate SQL queries.

Introduction   ◾    7

PERL INSTALLATION AND CONFIGURATION ON WINDOWS, LINUX, AND MACOS Installing Perl on our system, whether it is Windows, Linux, or Macintosh, is the first step. We must have a direct understanding of what the Perl programming language is and what it accomplishes. Perl is a dynamic, high-level, interpreted, general-purpose programming language. Perl was first designed for text processing, such as extracting the necessary information from a particular text file and converting text file to a new format. Perl supports both procedural and Object-Oriented programming. Perl is syntactically similar to C, making it accessible to C and C++ programmers. Programming in Perl is possible using any plain text editor, such as notepad, notepad++, or any other application. One may either utilize an online IDE or install one on their machine to make creating Perl routines easier. Using an IDE makes it simpler to create Perl code due to the IDE’s many capabilities, such as an intuitive code editor, debugger and compiler. Perl must be installed on a system before developing Perl codes and executing many exciting and beneficial operations. This may accomplish by following the detailed methods given below: Checking for a preinstalled version of Perl: Before we begin the installation of Perl, it is a good idea to check if it is already installed on your system. Many software applications require Perl to perform their operations, so a version of Perl may include in the software’s installation package. There is no need to redownload and reinstall Perl if this is the case. Macintosh also preinstalls Perl on its computers. Perl is preloaded on many Linux systems. Simply use the command prompt to see whether Perl is preloaded on your device. (For Windows, type cmd in the Run dialogue (window + R), for Linux, press Ctrl+Alt+T, and for macOS, press Control+Option+Shift.) Execute the following command now: perl -v

If Perl is already installed, a message with all the details of Perl’s version will be generated; otherwise, an error stating bad command or file name will be generated.

8   ◾    Mastering Perl

PERL DOWNLOAD AND INSTALLATION Perl download: • Before starting with installation process, we need to download it. For that, all versions of Perl for the Windows, Linux, and macOS are available on https://www.perl.org/get.html

Perl download.

• Install Perl by downloading it and following the installation instructions.

Starting with the Windows installation: • Completing the User’s License Agreement.

• Deciding what to install. • The installation procedure. • Completed installation. After finishing the installation procedure, any IDE or text editor may use to develop Perl codes, which can then be run on the IDE or the command prompt with the command: perl file1.pl

Introduction   ◾    9

Starting with the Linux installation: • Change the path to install Perl.

• Start the installation process. • Choosing the Perl Installation Directory. • Finishing the installation. • Once the installation procedure is complete, any IDE or text editor may be used to create Perl codes, which can then launch on the IDE or the command prompt with the command: perl file1.pl

Starting with the macOS installation: • Starting out.

• Finished with the User’s License Agreement. • Choosing a place for installation. • The installation procedure. • Installation is now complete. • After finishing the installation procedure, any IDE or text editor may use to develop Perl codes, which can then be run on the IDE or the command prompt with the command: Perl file.pl

HELLO WORLD PROGRAM Perl is a computer language explicitly developed for text processing. The acronym stands for Practical Extraction and Report Language. It is compatible with several systems, including Windows, Mac OS, and almost all UNIX variants. The Hello Everyone! program in each programming language provides novice programmers with a head start in learning the language.1 The result of the simple Hello everyone program is “Hello Everyone!” printed on the screen. A simple Perl program consists of the following execution steps: • Step 1: Transfer the file to the Perl interpreter.

10   ◾    Mastering Perl

In Perl, the first line always begins with the pair of characters #!. It instructs the Perl interpreter on how to execute the file. The file should relocate to the/usr/bin/Perl subdirectory, which contains the Perl interpreter. Therefore, the first line of the program will read as follows: #!/usr/bin/perl

• Step 2: Perl Pragma A pragma is a special module in the Perl package that has control over various features of Perl’s compile time or run time behavior, such as strictness or warnings. So the following two lines are as follows: use strict; use warnings;

• Step 3: Make use of the print() function. Finally, we use Perl’s print() method to display a string to display the output. print("Hello Everyone\n");

Example: #!/usr/bin/perl # Modules-used use strict; use warnings; # Print function print("Hello Everyone\n");

Important points: • The file must save with the extension .pl.

• The Perl package directory must be the same as where the program file is saved.

Introduction   ◾    11

HOW TO EXECUTE A PERL PROGRAM In general, there are two methods for running a Perl program: using online IDEs: We can run Perl programs without installing them by using various online IDEs. Using the command line: We can launch a Perl program using command line options. The following instructions explain how to launch a Perl program from the command line in Windows/Unix: Windows To begin, launch a text editor such as Notepad or Notepad++. Write the code in a text editor and save it as a .pl file. Ascertain that we have obtained and installed the most recent Perl version from https://www.perl.org/get.html. Open the command line and type Perl -v to see if the newest version of Perl has been correctly installed. Type Perl HelloEveryone.pl to build the code. If our code has no errors, it will run correctly and the output will be shown. Unix/Linux Follow the steps above to write code and save the file with the .pl extension. To download and install Perl, use the terminal application on our Unix/ Linux operating system and follow the steps below. Now, execute the command Perl -version to see if the newest version of Perl was correctly installed. Type Perl hello.pl to build the code. If our code has no errors, it will run correctly, and the output will show.

A PERL PROGRAM’S BASIC SYNTAX Perl is a dynamic, high-level, interpreted, general-purpose programming language. Perl was first designed for text processing, such as extracting the necessary information from a particular text file and converting text file to a new format. Perl supports both procedural and object-oriented programming. Perl is similar to C, making it accessible to C and C++ programmers. Perl follows a basic syntax for developing programs for applications and software and writing simple Perl programs, similar to those of other programming languages. This grammar features several predefined phrases such as keywords, variables for storing values, expressions, statements for performing logic,

12   ◾    Mastering Perl

loops for iterating through a variable value, blocks for combining statements, and subroutines for simplifying code. All of these elements, when combined, constitute a Perl program. The variables, statements, and other factors that make up a program’s syntax are used by every Perl program, whether it’s a simple code for adding two numbers or a complex one for launching web scripts. Variables Variables are user-defined words used to store the program’s values and utilized to evaluate the code. Every Perl program comprises values on which the code operates. These values cannot be edited or saved unless a variable is used. A value can only process if it is saved in a variable and the variable’s name is used. A value is data that is passed to the program to conduct a modification action. This data can be numbers, strings, characters, lists, etc. Example: Values: 15 peeks 25 Variables: $c = 15; $d = "peeks"; $e = 25;

Expressions Variables and an operator symbol make up Perl expressions. These expressions define the operation performed on the data given by the relevant code. In Perl, an expression is something that, when evaluated, returns a value. An expression can also be a value without any variables or operator symbols. It can be either an integer or a string with no variables. Example: Value 10 is an expression, $c + $d is an expression that returns their sum, etc.

A more complex expression is one that uses Regex to perform operations on strings and substrings.

Introduction   ◾    13

Comments Perl developers frequently utilize the comment system since things may quickly become complicated without it. Comments are essential information provided by developers to help the reader comprehend the source code. It describes the reasoning or a portion of it that is employed in the code. When we are no longer available to address queries about our code, comments are frequently helpful to someone who is maintaining or improving it. These are frequently noted as a good programming practice that does not affect program output but increases overall readability. In Perl, there are two kinds of comments: 1. Single-line comments: A single-line comment in Perl begins with the hashtag symbol (#) and continues until the end of the line. If the comment is more than one line, add a hashtag to the following line and continue the comment. Single-line comments in Perl have proven helpful in providing brief explanations for variables, function declarations, and expressions. The following code for an example of a one-line comment: #!/usr/bin/perl $d = 10; # Assigning value to $d $e = 30; # Assigning value to $e $c = $d + $e; # Performing operation print "$c"; # Printing result

2. A multi-line string as a comment: A multi-line comment in Perl is a chunk of text enclosed by “=” and “=cut.” They are useful when the remark content does not fit on a single line and must spread across lines. Multi-line comments or paragraphs provide documentation for people who are reading your code. Perl considers everything typed after the “=” sign to be a comment until a “= cut follows it.” Please remember that there should be no whitespace following the “=” symbol. See the following code snippet for an example of a multiline comment: #!/usr/bin/perl =Assigning values to The variable $d and $e =cut

14   ◾    Mastering Perl $d = 10; $e = 30; =Performing operation and printing result =cut $c = $d + $e; print "$c";

Statements A statement in Perl contains instructions for the compiler to conduct operations. These statements conduct the operations on the variables and values at the run-time. Every sentence in Perl must conclude with a semicolon(;). Basically, instructions put in the source code for execution are termed statements. There are several sorts of statements in the Perl programming language, such as assignment statements, conditional statements, and looping statements. These all allow the user to acquire the appropriate output. For example, n = 60 is an assignment statement. Multi-line statements: Statements in Perl may be expanded to one or more lines by simply separating them into pieces. Unlike other languages like Python, Perl looks for a semicolon to terminate the sentence. Every line between two semicolons is treated as a single sentence. When the programmer wants to execute extensive computations and cannot fit his statements onto one line, one may simply split it into numerous lines. Example: $z = $g + $h + $i + $j + $k + $l;

Block A block is a collection of statements that execute a related operation. Multiple statements in Perl can be performed concurrently (under a single condition or loop) by using curly braces ({}). This creates a block of statements that are all performed simultaneously. This block can use to optimize the program by grouping statements together. Variables declared within a block have a scope confined to that block and are useless outside of it. They will only be executed when that specific block is being run.

Introduction   ◾    15

Example: { $d = 25; $d = $d + 35; print($d); }

The variable $d in the preceding code has a scope confined to this specific block and is useless outside of it. The block above contains statements with operations that are related to one another. Functions or Subroutines A function/subroutine is a code block written in a program to execute a specified task. To better understand how functions work, we may compare functions in programs to people in a real-world workplace. Assume the manager assigns his staff the task of calculating the annual budget. So, how will this procedure be completed? The employee will obtain statics information from the employer, run calculations, compute the budget, and provide the results to his supervisor. Functions operate similarly. They accept information as an argument, run a set of statements, conduct operations on these parameters, and then return the output. Perl offers two primary types of functions: • Built-in functions: Perl has a large number of built-in library functions. These functions have already been coded and saved as functions. To use them, we just need to call them when needed, such as sin(), cos(), chr(), return(), and shift().

• User-defined functions: Perl allows us to write our own customized functions, known as user-defined functions or subroutines, in addition to the built-in functions. Using this, we may develop our code packages and call them whenever we need them. Loops Like any other language, Perl uses loops to execute a statement or a group of instructions repeatedly until and unless a specific condition is fulfilled. This allows the user to save time and effort by not writing the same code multiple times.

16   ◾    Mastering Perl

Perl offers several looping techniques: • for loop • for each loop • until loop • while loop • do…while loop • nested loops Whitespaces and Indentation In Perl, whitespaces are blank spaces used between variables and operators, between keywords, and so on. Whitespaces have no effect in Perl unless quote marks surround them. Whitespaces such as spaces, tabs, and newlines have the same meaning in Perl when used outside quotes. First example: $c = $d + $e; Here, spaces are of no use, it will cause no effect even if it is written as $c = $d + $e;

Second example: print "Peeks for Peeks"; will print Peeks for peeks whereas, print "Peeks for peeks"; will print Peeks for Peeks

In the preceding instances, whitespaces have no impact unless placed within quotations.

Introduction   ◾    17

Similarly, indentation is used to structure the code to make it easier for users to read. When a block of statements is utilized, indentation helps to reduce the code’s readability difficulty. Example: Using Indentation: { $c = $d + $e; print "$a"; } Without using Indentation: { $c = $d + $e; print "$c"; }

In the above example, both blocks will function identically; but indentation makes it more reader-friendly for scripts with a significant number of statements. Though using whitespaces and indentation in your Perl code is not required, it is a recommended practice. Keywords Keywords, often known as reserved words, are terms in a language used for internal processes or to indicate predefined actions. They have a unique significance for the compiler. As a result, these terms are not permitted to be used as variable names or objects. This will produce a compiletime error. Along with control words, keywords in Perl contain built-in functions. These keywords can occasionally be used as variable names, although this causes confusion and makes debugging such a program difficult. Example: One can use $print as a variable and keyword print().

18   ◾    Mastering Perl

DATA TYPES Data types define the sorts of data that can store in a valid Perl variable. Perl is a loosely typed programming language. There is no need to provide a data type while using the Perl program. The Perl interpreter will choose the type based on the context of the data. Perl has three data types, which are as follows: • Scalars • Arrays • Hashes Scalars A single data unit can be an integer, a floating-point value, a character, a string, a paragraph, or an entire web page. Example: # Program to demonstrate the # Scalars data types # integer assignment $age = 1; # string $name = "ABC"; # floating point $salary = 21.5; # displaying result print "Age is = $age\n"; print "Name is = $name\n"; print "Salary is = $salary\n";

Arrays Array is a variable that stores values of the same data type as a list. In Perl, we use the “@” symbol before the variable name to declare an array. @age=(20, 30, 40)

Introduction   ◾    19

It will generate an array of integers with the values 20, 30, and 40. The “$” symbol is used to access a single member in an array. $age[0]

Example: # Program to demonstrate # the Arrays data type #!/usr/bin/perl # creation of the arrays @ages = (43, 21, 29); @names = ("Peeks", "for", "Peeks"); # displaying result print "\$ages[0] = $ages[0]\n"; print "\$ages[1] = $ages[1]\n"; print "\$ages[2] = $ages[2]\n"; print "\$names[0] = $names[0]\n"; print "\$names[1] = $names[1]\n"; print "\$names[2] = $names[2]\n";

Hashes It is a collection of key-value pairs. It is also known as associative arrays. We use the “%” symbol in Perl to declare a hash. We utilize the “$” symbol followed by the key in brackets to get to a specific value. Example: # Program to demonstrate the # Hashes data type # Hashes %data = ('PFP', 7, 'for', 4, 'Peeks', 11); #displaying result print "\$data{'PFP'} = $data{'PFP'}\n"; print "\$data{'for'} = $data{'for'}\n"; print "\$data{'Peeks'} = $data{'Peeks'}\n";

20   ◾    Mastering Perl

This chapter covered Perl introduction, installation and environment setup and Hello World Program.

NOTE 1. Hello World Program in Perl.

Chapter

2

Fundamentals of Perl

IN THIS CHAPTER

➢➢ Modes of Writing ➢➢ Boolean Values ➢➢ Operators ➢➢ Variables ➢➢ Modules in Perl ➢➢ Packages in Perl ➢➢ Number and Its Types ➢➢ Directories with CRUD Operations In the previous chapter, we discussed Perl basic, and in this chapter, we will cover packages, module operators, variables, and modes of writing.

PERL CODE WRITING METHODS Perl is a dynamic, high-level, interpreted, general-purpose programming language. Perl supports both procedural and object-oriented programming. Perl was initially designed only for system administration and text processing, but subsequent versions included the ability to manage regular expressions, network sockets, etc. Perl is syntactically similar to other commonly known programming languages, making it easy to write and understand. Perl is a free-form DOI: 10.1201/9781003358442-2

21

22   ◾    Mastering Perl

programming language, meaning it may be written, formatted, and indented according to the user’s needs. A Perl program consists of a series of statements, loops, subroutines, etc., which facilitates navigation around the code. Every Perl statement must conclude with a semicolon (;). Perl, like other languages, provides several writing and execution modes for Perl code. These modes may be classified according to their compatibility with writing and mode of execution in the following ways: • Interactive mode • Script mode • One-liner mode These modes can be used on the command line with the Perl keyword or in online Integrated Development Environment (IDEs) as a block of code. Along with the installation package, Perl has its own inbuilt IDE. Interactive Mode Interaction with the interpreter is signified by the interactive method of creating Perl code. Interactive mode is a wonderful approach to begin programming since it allows you to examine the flow of code line by line and simplifies the debugging process. With Perl debugger, interactive mode in Perl can be utilized on the command line. This interpreter is often called REPL – Read, Evaluate, Print, Loop. Interactive mode enables the immediate creation and execution of code without creating a temporary file to save the source code. Using Perl debugger, the built-in Perl command line or the Windows command prompt may be used as a REPL. This debugger can be used with a Perl application with the following command: perl -de1

The user must write the code line by line in the interactive mode of writing Perl code, which is run simultaneously. Perl’s interactive mode may be run directly from the command line, without the need for a debugger. This can be done by using the following command: perl -e Code_statement;

Fundamentals of Perl   ◾    23

This statement utilizes the -e parameter to avoid script creation and allows the code to run without the debugger on the command line. This way of writing in interactive mode does not allow the user to create multi-line code as it does in the debugger. This mode is not recommended for long programs. Interactive mode is useful for teaching new programmers the fundamentals of programming, but it may become cumbersome and tedious when dealing with more than a few lines of code. Script Mode Script mode in Perl is used to develop Perl programs that include more than a few lines of code and are too complicated for interactive mode. Using a text editor, script mode in Perl can be used to develop a Perl program; it is saved in a file called a script, and then the script file is run using the command line. This file must be saved with the. pl extension and stored in the same directory as the directory path specified on the command line. This script is then executed from the command line using the following command: perl FileName.pl

Code is typed in a text editor (notepad, for example) and saved as a Perl program.pl script. Unlike the interactive mode, script mode in Perl cannot provide output for each individual expression. In the interactive mode, the expression is evaluated, and the result is presented automatically, while in the script mode, the expression is evaluated, but the result is not displayed until prompted. Online IDEs also provide script mode, which is used to develop and run Perl code without manually putting it in a file. In these IDEs, compiled code is saved in memory as a temporary file that is only useful when the code is run, and the browser containing the IDE is open. Once the page is refreshed, this temporary file is destroyed, and memory space is released. Online IDEs have simplified the execution of codes since they need less effort than the script mode, in which files must be saved in the machine’s memory. This quickens the compilation and execution of code. These online IDEs, although convenient for programmers, have significant restrictions, such as the inability to conduct file handling operations unless the file is

24   ◾    Mastering Perl

uploaded to their server, which poses a risk to sensitive data. Compilers that operate through the command line allow for such file manipulation capabilities. Here is an example of a Perl program that adds two integers using an online IDE: #!/usr/bin/perl # add two numbers program # Assigning values to the variables $var1 = 20; $var2 = 35; # Evaluating result $result = $var1 + $var2; # Printing result print "Result after the addition is: $result";

One-Liner Mode Perl also has a one-liner mode, allowing us to type and run a minimal code script right from the command line. This is done to prevent creating files to store scripts for codes that are not too long. With the use of the following command, these codes can be written on a single line in command line mode: perl -e

This command is used to write and execute one-liner code at the command line by enclosing it in double quotation marks. The -e flag in the preceding command informs the compiler that the code’s script is not kept in any sort of file but is written in the double codes immediately after this flag. These one-liners may be quite handy for making rapid modifications such as obtaining information and modifying file contents. Some programmers avoid using one-liners because they can become clumsy when the script becomes too long. While some programmers prefer doing this since one-liners are faster than scripts because they are not stored in files.

Fundamentals of Perl   ◾    25

BOOLEAN VALUES IN PERL True and False are considered boolean values in most computer languages. However, Perl does not provide the boolean type for True and False. When a function returns True or False, a programmer might use the word “boolean.” Scalar values, like conditional expressions (if, while, etc.), will return true or false. Example: # Perl Code to demonstrate boolean values   # variable assigned value 0 $x = 0; # checking whether x is true or false if ($x) { print "x is True\n"; } else { print "x is False\n"; } # variable assigned value 2 $y = 2; # checking whether y is true or false if ($y) { print "y is True\n"; } else { print "y is False\n"; }

True values: In Perl, True values are any non-zero numbers other than zero. In Perl, string constants such as “true,” “false,” “00” (2 or more 0 characters), and “0n”(a zero followed by a newline character in the string) are also considered true values.

26   ◾    Mastering Perl

Example: # Perl Code to demonstrate True values # variable assigned value 5 $x = 5; # checking whether x is true or false if ($a) { print "x is True\n"; } else { print "x is False\n"; } # string variable assigned white # space character $y = ' '; # checking whether y is true or false if ($y) { print "y is True\n"; } else { print "y is False\n"; } # string variable assigned 'false' # value to it $m = 'false'; # checking whether c is true or false if ($m) { print "m is True\n"; } else { print "m is False\n";

Fundamentals of Perl   ◾    27 } # string variable assigned "0\n" # value to it $n = "0\n"; # checking whether d is true or false if ($n) { print "n is True\n"; } else { print "n is False\n"; }

False values: In Perl, false values are empty string or a stringcv containing a single digit 0 or undef value and zero. Example: # Perl Code to demonstrate False values # variable assigned value 0 $x = 0; # checking whether x is true or false if ($x) { print "a is True\n"; } else { print "x is False\n"; } # string variable assigned empty string $y = ''; # checking whether y is true or false if ($y)

28   ◾    Mastering Perl { print "y is True\n"; } else { print "y is False\n"; } # string variable assigned undef $m = undef; # checking whether m is true or false if ($m) { print "m is True\n"; } else { print "m is False\n"; } # string variable assigned "" # value to it $n = ""; # checking whether n is true or false if ($n) { print "n is True\n"; } else { print "n is False\n"; }

Note: For the conditional check, where the user must compare two distinct variables, if they are not equal, it returns False; otherwise, it returns True. Example: # Perl Program demonstrate conditional check # variable initialized with string $c = "PFP";

Fundamentals of Perl   ◾    29 # using the if statement if ($c eq "PFP") { print "Return True\n"; } else { print "Return False\n"; }

OPERATORS Operators are the building blocks of any computer language, allowing the programmer to perform various operations on operands. In Perl, the symbols for operators will differ depending on the kind of operand (like scalars and strings). Operators are classified based on their many functions1: • Arithmetic operators • Relational operators • Ternary operators • Logical operators • Bitwise operators • Assignment operators

Types of operators.

30   ◾    Mastering Perl

Arithmetic Operators There are various types of arithmetic operators. Addition These are used to execute arithmetic and mathematical operations on operands. To add the values of the two operands, use the “+” operator. As an example: $x = 15; $y = 20; print $x + $y; Here Result will be 25

Subtraction The “−” operator subtracts the right-hand operand from the left-hand operand. As an example: $x = 15; $y = 20; print $x - $y; Here Result will be 5

Multiplication The “*” operator multiplies the values on both sides of the operator. As an example: $x = 15; $y = 20; print $x * $y; Here Result will be 300

Division When the first operand is divided by the second, the “/” operator returns the remainder. As an example: $x = 40; $y = 20; print $x / $y; Here Result will be 20

Fundamentals of Perl   ◾    31

Modulus The modulus operator (%) divides the left-hand operand from the righthand operand and returns the remainder. As an example: $x = 10; $y = 15; print $x % $y; Here Result will be 5

Exponent Operator The “**” operator is used to calculate the exponential (power) of operands. As an example: $x = 2; $y = 3; print $x ** $y; Here Result will be 8

The aim of this program is to describe the following arithmetic operators: # Perl Program to illustrate Arithmetic Operators # Operands $x = 10; $y = 4; # using arithmetic operators print "The Addition is: ", $x + $y, "\n"; print "The Subtraction is: ", $x - $y, "\n" ; print "The Multiplication is: ", $x * $y, "\n"; print "The Division is: ", $x / $y, "\n"; print "The Modulus is: ", $x % $y, "\n"; print "The Exponent is: ", $x ** $y, "\n";

Relational Operators When comparing two values, relational operators are employed. These operators will either return 1 (true) or 0 (false). These operators are also known as the equality operators. These operators use various symbols to work on strings. We may use this to learn about the comparison operators operation on string.

32   ◾    Mastering Perl

• Equal to operator: “==” Determine whether two values are equal. If equals, return 1 else return nothing. • Not equal to operator: “!=” Check to see whether the two values are equivalent. If the values are not equal, 1 is returned; else, nothing is returned. • Comparison of equal to operator: “< = >” If the left operand is smaller than the right operand, the result is −1; otherwise, the result is 0. • Greater than operator: “>” If the left operand is greater than the right operand, 1 is returned; else, nothing is returned. • Less than operator: “=” If the left operand is larger than or equal to the right operand, 1 is returned; otherwise, nothing is returned. • Less than equal to operator: “ $y) { print "Greater Than Operator is True\n"; } else { print "Greater Than Operator is False\n"; } if ($x < $y) { print "Less Than Operator is True\n"; } else { print "Less Than Operator is False\n"; } if ($x >= $y) { print "Greater Than Equal To Operator is True\n"; } else { print "Greater Than Equal To Operator is False\n"; } if ($x 2;

Fundamentals of Perl   ◾    37 print $z; Output: 15 Explanation: 60 / 2 = 40 40 / 2 = 20

---(1) ---(2)

Program: To show how bitwise operators work: # Perl Program to illustrate Bitwise operators #!/usr/local/bin/perl use integer; # Operands $x = 100; $y = 2; # Bitwise AND Operator $result = $x & $y; print "Bitwise AND: ", $result, "\n"; # Bitwise OR Operator $result = $a | $b; print "Bitwise OR: ", $result, "\n"; # Bitwise XOR Operator $result = $x ^ $y; print "Bitwise XOR: ", $result, "\n"; # Bitwise Complement Operator $result = ˜$x; print "Bitwise Complement: ", $result, "\n"; # Bitwise Left Shift Operator $result = $x > $y; print "Bitwise Right Shift: ", $result, "\n";

Assignment Operators It is used to assign value to the variable. The assignment operator’s left operand is a variable, while the assignment operator’s right operand is a value.

38   ◾    Mastering Perl

The following are examples of assignment operators: • “=” (Simple assignment): The most basic assignment operator. This operator assigns the variable on the left the value on the right. As an example: $x = 20; $y = 40;

• “+=”(Add assignment): A combination of the “+” and “=” operators. This operator first adds current value of the variable on the left to value on the right, and then assigns result to the variable on the left. As an example: ($x += $y) can be written as ($x = $x + $y)

• If the initial value of a is 5, then ($a += 6) = 11. • “−=”(Subtract assignment): This operator combines the “−” and “=” operators. This operator subtracts the variable’s current value from the value on right and assigns the resulting value to the variable on the left. As an example: ($x -= $y) can be written as ($x = $x - $y)

• If the initial value of a is 8, then ($a −= 6) = 2. • “*=”(Multiply assignment): This operator combines the “*” and “=” operators. The variable on the left is multiplied by the value on the right, and the result is assigned to a variable on the left. As an example: ($x *= $y) can be written as ($x = $x * $y)

• If the initial value of a is 5, then ($x *= 6) = 30. • “/=”(Division assignment): This operator combines the “/” and “=” operators. This operator divides the current value of the variable on the left by the value on the right and allocates the result to the variable on the left. As an example: ($x /= $y) can be written as ($x = $x / $y)

• If the initial value stored in a is 6, then ($x /= 2) = 3.

Fundamentals of Perl   ◾    39

• “ % =”(Modulus assignment): This operator combines the “%” and “=” operators. This operator modifies the current value of the variable on the left by the value on the right before assigning the result to the variable on the left. As an example: ($x %= $y) can be written as ($x = $x % $y)

• If the initial value stored in a is 6, then ($a percent = 2) = 0. • “**=”(Exponent assignment): This operator is a mixture of the “**” and “=” operators. This operator multiplies the current value of the variable on the left by the value on the right before assigning the result to the variable on the left. As an example: ($x **= $y) can be written as ($x = $x ** $y)

• If the initial value stored in a is 6, then ($a **= 2) = 36. Program: To illustrate how assignment operators function: # program to demonstrate working of Assignment Operators #!/usr/local/bin/perl # taking two variables & using # the simple assignments operation $x = 8; $y = 5; # using the Assignment Operators print "The Addition Assignment Operator: ", $x += $y, "\n"; $x = 8; $y = 4; print "Subtraction Assignment Operator: ", $x -= $y, "\n" ; $x = 8; $y = 4; print "Multiplication Assignment Operator: ", $x*=$y, "\n";

40   ◾    Mastering Perl $x = 8; $y = 4; print "Division Assignment Operator: ",$x/=$y, "\n"; $x = 8; $y = 5; print "Modulo Assignment Operator: ", $x%=$y,"\n"; $x = 8; $y = 4; print "Exponent Assignment Operator: ", $x**=$y, "\n";

Ternary Operator It is conditional operator, which is simple version of an if else statement. The term “ternary” refers to fact that it has three operands. Depending on the value of Boolean expression, it will return one of two values. Syntax: condition?

firstexpression : secondexpression;

Example: # Perl program to demonstrate working # of the Ternary Operator $c = 5; $d = 10; # To find which value is greater # Using the Ternary Operator $result = $c > $d? $c : $d; # displaying the output print "Larger Number is: $result"

Note: The condition in the ternary operator may also be any expression generated by utilizing other operators such as relational operators and logical operators.

Fundamentals of Perl   ◾    41 # Perl program to demonstrate working # of Ternary Operator by using the expression # as a condition # here maximum value can be 200 $MAX_VALUE = 200; # suppose user provide value $user_value = 666; # To find which whether user provided # value is satisfying maximum value # or not by using the Ternary Operator $result = $user_value val1, key2=>val2, key3=>val3,…);

Example: %itempairs = ("Grapes" =>12, "Apple'=>5); %pairrandom = ("Hello" =>7, "Bye"=>8);

Modification of a Variable Perl allows us to change the values of variables after they’ve been declared. A variable can change in a variety of ways: • A scalar variable’s value can change simply by redefining it.

Fundamentals of Perl   ◾    43

Example: $name = "Seema"; # This can modify by simply # redeclaring variable $name. $name = "Sahil";

• An array element can update by passing its index to the array and assigning a new value to it. Example: @array = ("A", "B", "C", "D", "E"); # If the value of second variable is to # modify then it can done by @array[2] = "4"; # $array[2] = "4"; is alternate way of updating the value in array. # This will change array to, # @array = ("A", "B", "4", "D", "E");

• A hash value can change by using its key. Example: %Hash = ("A", 20, "B", 30, "C", 40) # This will modify the value # assigned to Key 'B' $Hash{"B"} = 56;

Variable Interpolation Perl provides many ways for assigning a string to a variable. This may be accomplished by using single quotes, double quotes, the q-operator, the double-q operator, and so forth. The use of single and double quotes for string writing is the same; however, there is a minor difference in how they operate. Strings enclosed in single quotes display the content contained within them exactly as typed. Example: $name = "Seema" print 'Hello $name\nHow are you doing?'

44   ◾    Mastering Perl

Strings enclosed in double quotes, on the other hand, replace the variables with their values before displaying the string. It even replaces the escape sequences with their correct implementation. Example: $name = "Seema" print "Hello $name\nHow are you doing?"

Example code: #!/usr/bin/perl use Data::Dumper; # Scalar-Variable $name = "PeeksForPeeks"; # Array Variable @array = ("P", "E", "E", "K", "S"); # Hash Variable %Hash = ('Welcome', 10, 'to', 20, 'Peeks', 40); # Variable-Modification @array[2] = "F"; print "The Modified Array is @array\n"; # Interpolation of a Variable # Using the Single Quote print 'Name is $name\n'; # Using the Double Quotes print "\nName is $name"; # Printing the hash contents print Dumper(\%Hash);

VARIABLES AND ITS TYPES Variables are reserved memory locations for storing values. This means that creating a variable frees up memory space. The data type of a variable assists the interpreter in allocating memory and deciding what to store in

Fundamentals of Perl   ◾    45

reserved memory. Variables can thus store integers, decimals, or strings by assigning different data types to the variables. Perl has three basic data types, which are as follows: • Scalars • Arrays • Hashes As a result, Perl will employ three types of variables. A scalar variable, preceded by a dollar sign ($), can store a number, a string, or a reference. An array variable stores ordered lists of scalars, denoted by the @ sign. The hash variable, preceded by sign %, will be used to store sets of key/value pairs. Creating Variables To reserve memory space, Perl variables do not need to be explicitly declared. Like in other computer languages, the operand to the left of the “=” operator is the variable’s name, and the operand to the right of the “=” operator is the value stored in the variable. As an example: $age = 30; $name = "Sima"; $rollno = 32; Here 30, "Sima" and 32 are the values assigned to $age, $name and $roll no variables, respectively.

Scalar Variables A scalar is a single data unit. The data could be an integer number, a floating-point number, a character, a string, a paragraph, or an entire web page. Here’s an example of how to use scalar variables: #!/usr/bin/perl # Assigning the values to scalar # variables $age = 30; $name = "Sima"; $rollno = 32;

46   ◾    Mastering Perl # Printing the variable values print "Age = $age\n"; print "Name = $name\n"; print "Roll no = $rollno\n";

Array Variables An array variable stores ordered list of scalar values. Array data type variables are preceded by “at” (@) sign. The dollar sign ($) refers to a single array element with the variable name followed by the element’s index in square brackets. Here’s an example of using an array variable: #!/usr/bin/perl # Assigning the values to Array variables @ages = (43, 70, 33); # @ is used to declare # the array variables @names = ("ABC", "DEF", "GHI"); # Printing values of Arrays print "\$ages[0] = $ages[0]\n"; print "\$ages[1] = $ages[1]\n"; print "\$ages[2] = $ages[2]\n"; print "\$names[0] = $names[0]\n"; print "\$names[1] = $names[1]\n"; print "\$names[2] = $names[2]\n";

We used “\” before the “$” sign to print it as a statement. Otherwise, Perl will interpret it as a variable and print the value stored in it. Hash Variables Hash is a collection of the key-value pairs. Hash variables are preceded by a modulus (%) sign. In the hash, keys are used to refer to a single variable. In curly brackets, the hash variable name is followed by the key associated with the value to access these elements. Here is a simple example of a Hash variable: #!/usr/bin/perl # Defining Hash variable using '%' %data = ('ABC', 55, 'DEF', 80, 'GHI', 44);

Fundamentals of Perl   ◾    47 # Printing values of print "\$data{'XYZ'} print "\$data{'LGH'} print "\$data{'KMR'}

Hash variables = $data{'ABC'}\n"; = $data{'DEF'}\n"; = $data{'GHI'}\n";

Variable Context Perl treats the same variable differently depending on the context, i.e. the situation in which a variable is used. Example: #!/usr/bin/perl # Defining Array variable @names = ('ABC', 'DEF', 'GHI'); # Assigning values of the array variable # to another array variable @copy = @names; # Assigning values of the Array variable # to a scalar variable $size = @names; # Printing values of new variables. print "The Given names are : @copy\n"; print "The Number of names are : $size\n";

@names is an array that has been used two times in this context. First, we copied it into other array, i.e. a list, so that it would return all the elements if the context was a list context. The same array is then attempted to be stored in a scalar context, which by default returns just the number of elements in this array. The table below depicts the various contexts: S. no.

1. 2.

Context and description

Scalar In a scalar context, assignment to a scalar variable evaluates the value to the right of “=”. List In a list context, assignment to an array or a hash evaluates the right of “=”. (Continued)

48   ◾    Mastering Perl S. no.

3. 4. 5.

Context and description

Boolean A boolean context is a location where an expression is evaluated to see whether it is true or false. Void This context does not care what the return value is, and it doesn’t even want one. Interpolative This context will only appear within quotation marks (“”) or with things that behave like quotation marks (“”).

SCOPE OF VARIABLES The scope of the variable is the area of program where the variable is accessible. The visibility of variables in a program is also referred to as a scope. We can declare global variables or private variables in Perl. Lexical variables are another name for private variables. The Scope of Global Variables Global variables can be used within any function or block that has been created within the program. It is visible throughout the program. Global variables can be used directly and are accessible from anywhere in the program. First example: At the start of the code, the variable $name is declared. It will be visible until the end of the file. Even within blocks. Even if they are included in the function declarations. If we change the variable within the block, the value for the rest of the code will change, even outside the block. #!/usr/bin/perl # Defining Array variable @names = ('ABC', 'DEF', 'GHI'); # Assigning values of the array variable # to another array variable @copy = @names; # Assigning values of the Array variable # to a scalar variable $size = @names;

Fundamentals of Perl   ◾    49 # Printing values of new variables. print "Given names are : @copy\n"; print "Number of names are : $size\n"; # Perl program to illustrate # Scope of Global variables # declaration of the global variable $name = "PFP"; # printing global variable print "$name\n"; # # # # # {

global variable can use inside a block, hence the we are taking a block in which we will print the value of $name i.e. global variable

# here GFG will print print "$name\n"; # values in the global variable can be # changed even within block, # hence value of $name is # now changed to "PeeksforPeeks" $name = "PeeksforPeeks"; # print function prints # "PeeksforPeeks" print "$name\n"; } # changes made inside the above block' # are reflected in the whole program # so here PeeksforPeeks will print print "$name\n";

Second example: # program to illustrate the # Scope of Global variables

50   ◾    Mastering Perl # declaration of the global variables $name = "PFP"; $count = 1; # printing global variables print $count." ".$name."\n"; $count++; # Block starting { # global variable can use inside # a block, so below statement will # print PFG and 1 print $count." ".$name."\n"; # incrementing the value of # count inside block $count++; } # taking function sub func { # Global variable, $count and $name, # are accessible within the function print $count." ".$name."\n"; } # calling function func();

Lexical Variables’ Scope (Private Variables) Private variables in Perl are defined by prefixing the variable with “my” keyword. The “my” keyword limits variables inside a specified function or block. A block can either be a for loop, a while loop, or a block of code surrounded by curly braces. The local variable’s scope is local; it exists just between these two curly brackets (block of code); this variable does not exist outside of this block. These variables are sometimes referred to as lexical variables. When private variables are used inside a function or block, the global variables with the same name are hidden. When a subroutine is called with a private

Fundamentals of Perl   ◾    51

variable, that variable may utilize inside the procedure. When the procedure terminates, the private variables are no longer usable. Example: # program to illustrate the # scope of private variables # declaration of the global variable $name = "Global"; $count = 1; # printing the global variables print $count." ".$name."\n"; # incrementing the value of count # i.e it become 2 $count++; # block starting { # declaring private variable by using my # keyword which can only use # within this block my $new_name = "Private"; # global variables are # accessible inside the block print $count." ".$name."\n"; # incrementing the value # of global variable # here it become 3 $count++; print $name." and ".$new_name."\n"; } # $new_name variable cannot # be used outside, hence nothing # is going to print

52   ◾    Mastering Perl print "Variable defined in the above block: ".$new_name."\n"; # declaring function sub func { # this private variable declaration # hides global variable which define # in the beginning of program my $name = "Hide"; print $count." ".$name."\n"; } # calling function func();

Package Variables Package scoping is an additional type of scoping in Perl. This is used when we need to create variables that can only be used in different namespaces. In every Perl program, the default namespace is “main.” The package keyword is used in Perl to define namespaces. Example: # program to illustrate  # Package Variables # variable declared in the # main namespace $var1 = "Main Namespace"; print "The Value of Var1: ".$var1."\n"; # package declaration # Pack1 is package package Pack1; # since $var1 belongs to main namespace, # so nothing will print inside the Pack1 # namespace print "The Value of var1: ".$var1."\n";

Fundamentals of Perl   ◾    53 # variable declared in Pack1 namespace # having same name as the main namespace $var1 = "Pack1 Namespace"; # here $var1 belongs to Pack1 namespace print "The Value of var1: ".$var1."\n"; # in-order to print variables # from both namespace, use # the following method print "The Value of var1: ".$main::var1."\n"; print "The Value of var1: ".$Pack1::var1."\n";

In Perl, the “our” keyword only creates an alias for an existing package variable with the same name. Only within lexical scope of the “our” declaration can a package variable be used without qualifying it with the package name. A variable declared with our keyword is an alias for a package variable visible throughout its entire lexical scope, including across package boundaries. # program to illustrate the use # of our keyword # Pack1 namespace declared # by using package keyword package Pack1; # declaring $Pack1::first_name # for the rest of lexical scope our $first_name; $first_name = "Shashank"; # declaring $Pack1::second_name for the # only this namespace $second_name; $second_name = "Sharma"; # Pack2 namespace declared package Pack2; # prints value of $first_name, as it # refers to $Pack1::first_name

54   ◾    Mastering Perl print "first_name = ".$first_name."\n"; # It will print nothing as the $second_name # doesn’t exist in Pack2 package scope print "second_name = ".$second_name."\n";

MODULES IN PERL In Perl, a module is a group of connected subroutines and variables that execute a set of programming tasks. Perl modules can reuse. The comprehensive Perl archive network (CPAN) hosts several Perl modules. These modules are divided into several categories, including network, CGI, XML processing, and database interface. Making a Perl Module A module’s name must be the same as the Package’s name and conclude with the .pm extension. Example: package Calculator; # Defining sub-routine for Multiplication sub multiplication { # Initializing Variables x & y $x = $_[0]; $y = $_[1]; # Performing operation $x = $x * $y; # Function to print Sum print "\n***Multiplication is $x"; } # Defining sub-routine for the Division sub division { # Initializing Variables x & y $x = $_[0]; $y = $_[1];

Fundamentals of Perl   ◾    55 # Performing operation $x = $x / $y; # Function to print answer print "\n***Division is $x"; } 1;

The file is called “Calculator.pm” and is located in the directory Calculator. To return true value to the interpreter, 1 is placed at the end of the function. Instead of 1, Perl accepts anything true. Importing and Using a Perl Module We utilize need or use functions to import this calculator module. :: is used to access a function or variable from a module. Here’s an example to show: #!/usr/bin/perl # Using Package 'Calculator' use Calculator; print "Enter the two numbers to multiply"; # Defining values to the variables $x = 15; $y = 20; # Subroutine-call Calculator::multiplication($x, $y); print "\nEnter the two numbers to divide"; # Defining values to variables $x = 55; $y = 65; # Subroutine call Calculator::division($x, $y);

Utilizing Module Variables Declaring variables from various packages before using them allows them to be utilized.

56   ◾    Mastering Perl

Example: #!/usr/bin/perl package Message; # Variable-Creation $username; # Defining-subroutine sub Hello { print "Hello $username\n"; } 1;

The module’s Perl file is as follows: #!/usr/bin/perl # Using the Message.pm package use Message; # Defining the value to variable $Message::username = "Peeks"; # Subroutine-call Message::Hello();

Making Use of predefined Modules Perl has several predefined modules that can be used in Perl applications at any time. Such as “strict” and “warnings”. Example: #!/usr/bin/perl use strict; use warnings; print" Hello This program uses the pre-defined Modules";

Fundamentals of Perl   ◾    57

PERL PACKAGES A Perl package is a set of code that resides in its namespace. A Perl module is a package defined in a file with the same name as the package and the extension .pm. A variable or function with same name may exist in two distinct modules. Any variable that isn’t in a package belongs to the main package. As a result, all variables used are part of the “main” package. The declaration of extra packages ensures that variables from various packages do not interfere with one another. Perl Module Declaration The module’s name must be the same as the package name and has a .pm extension. Example: package Calculator; # Defining sub-routine for the Addition sub addition { # Initializing Variables x & y $x = $_[0]; $y = $_[1]; # Performing the operation $x = $x + $y; # Function to print Sum print "\n***Addition is $x"; } # Defining sub-routine for the Subtraction sub subtraction { # Initializing Variables x & y $x = $_[0]; $y = $_[1]; # Performing the operation $x = $x - $y;

58   ◾    Mastering Perl # Function to print difference print "\n***Subtraction is $x"; } 1;

The file is called “Calculator.pm” and is stored in the directory Calculator. To return true value to the interpreter, 1 is written after the function. Instead of 1, Perl accepts anything that is true. Making Use of a Perl Module We utilize need or use functions to access this calculator module. :: is used to access a function or variable from a module. Here’s an example to show: #!/usr/bin/perl # Using Package 'Calculator' use Calculator; print "Enter the two numbers to add"; # Defining values to variables $x = 10; $y = 20; # Subroutine-call Calculator::addition($x, $y); print "\nEnter the two numbers to subtract"; # Defining values to the variables $x = 30; $y = 10; # Subroutine-call Calculator::subtraction($x, $y);

Using a Different Directory to Access a Package If a file accessing the package is located outside the directory, we use “::” to specify the module’s path. For example, because a file that uses the calculator module is outside the calculator package, we write Calculator :: Calculator for loading the module, where the value on the left of the “::”

Fundamentals of Perl   ◾    59

represents the package name and the value on the right of the “::” represents the Perl module name. To illustrate, consider the following example: #!/usr/bin/perl use GFG::Calculator; # Directory_name::module_name print "Enter the two numbers to add"; # Defining values to variables $x = 10; $y = 20; # Subroutine-call Calculator::addition($x, $y); print "\nEnter the two numbers to subtract"; # Defining values to variables $x = 30; $y = 10; # Subroutine-call Calculator::subtraction($x, $y);

Utilizing Module Variables Declaring variables from various packages before using them allows them to be utilized. The following example exemplifies this. #!/usr/bin/perl package Message; # Variable-Creation $username; # Defining-subroutine sub Hello { print "Hello $username\n"; } 1;

60   ◾    Mastering Perl

The module’s Perl file is as follows. #!/usr/bin/perl # Using the Message.pm package use Message; # Defining value to the variable $Message::username = "XYZ"; # Subroutine-call Message::Hello();

Begin and End Block When we wish to run some code at the beginning and some code at the conclusion, we utilize the BEGIN and END blocks. The codes within BEGIN... are run at the beginning of the script, while the codes within END... are executed at the end. This is demonstrated in the following program: #!/usr/bin/perl # Predefined BEGIN block BEGIN { print "In begin block\n"; } # Predefined END block END { print "In end block\n"; } print "Hello Everyone;\n";

NUMBER AND ITS TYPES IN PERL In Perl, a number is a mathematical object that may use to count, measure, and perform different mathematical operations. A numeral is a notational sign that symbolizes a number. In addition to being used in mathematical operations, these numerals are also utilized for ranking (in the form of serial numbers).

Fundamentals of Perl   ◾    61

Example: 2, 4, -6, 7.6, -8.9, 057, 1.87e-10, 0xFFFF

These numbers can be classified into several sorts based on their application: • Integers: Perl integers are represented as decimal numbers with a base of 10. These numbers might be both positive and negative. On the other hand, Perl employs “_” to represent large integer values to improve readability. Example: 213,254,484 is represented as 213_254_484 #!/usr/bin/perl # Positive-Integer $c = 30; # Negative-Integer $d = -25; # Big Integer-Number $e = 213_254_484; # Printing these numbers print("Positive Integer: ", $c, "\n"); print("Negative Integer: ", $d, "\n"); print("Big Integer: ", $e, "\n");

• Floating point numbers: In Perl, floating-point numbers have an integer and fractional values separated by a decimal point. The integer component of a floating number can be positive or negative, while the fractional component can only be positive. In Perl, floating numbers may be expressed in two ways: • Fixed point: The decimal point is fixed in this format. This decimal point marks the beginning of the fractional portion. Example: 22.5978

62   ◾    Mastering Perl

• Scientific: This representation comprises two parts: the significand (the actual number) and the exponent (the power of 10 by which the significand is multiplied). Example: 1.23567e-3 represents 1235.67 #!/usr/bin/perl # Positive Floating-Number $c = 20.5647; # Negative Floating-Number $d = -15.2451; # Scientific-value $e = 123.5e-10; # Printing these numbers print("Positive Number: ", $c, "\n"); print("Negative Number: ", $d, "\n"); print("Scientific Number: ", $e, "\n");

• Hexadecimal numbers: Hexadecimal numerals have a base of 16, ranging from 0 to 15, and are written as 0xa with “0x” before the number, whereas “a” here represents the value of 10 in Hex form. These alphabets represent 10–15 and range from “a” to “f”. Hexadecimal numerals can have both positive and negative values. Example: 0xe represents 14 in the Hex, and 0xc represents 12 #!/usr/bin/perl # Positive Hexadecimal Number $c = 0xc; # Negative Hexadecimal Number $d = -0xe;

Fundamentals of Perl   ◾    63 # Printing these values print("Positive Hex Number: ", $c, "\n"); print("Negative Hex Number: ", $d, "\n"); # To print Hex value printf("Value in the Hex Format: %c", $c);

As a result, “% x” is used to display the value of the number in hexadecimal format, as illustrated above. • Octal numbers: Octal numbers are numbers with a base of 8, ranging from 0 to 7. These numbers are represented as 057, with the number preceded by a “0” and the remainder being the octal value of the requisite decimal number. Octal numbers, like other sorts, can be both positive and negative. Example: For octal number 057 decimal equivalent will be 47. #!/usr/bin/perl # Positive Octal Number $c = 074; # Negative Octal Number $d = -074; print("The Positive Octal number: ", $c, "\n"); print("The Negative Octal number: ", $d, "\n"); # To print value in the Octal Form printf("Value in Octal Form: %o", $c);

“% o” is used here to output the value in the octal form. • Binary numbers: Binary numbers have a base of two, meaning they have only two values: 0 and 1. These numbers are written as 0b1010, with the letter “0b” before the number. Example: For binary number '0b1010' decimal equivalent will be '10'

64   ◾    Mastering Perl #!/usr/bin/perl # Positive Binary-Number $c = 0b1010; # Negative Binary-Number $d = -0b10110; # Printing these values print("The Positive Binary Number: ", $c, "\n"); print("The Negative Binary Number: ", $d, "\n"); # Printing in the unsigned binary form printf("Value in unsigned Binary Form: %b", $c);

“% b” is used in the above code to display the number in its binary form.

DIRECTORIES WITH CRUD OPERATIONS IN PERL Perl is a universal and cross-platform programming language that is mainly used for text manipulation and is utilized in developing several software applications such as web development and graphical user interface applications. It is favored over other programming languages because it is quicker and more powerful, and it also includes many shortcuts that aid in creating rapid scripts. In computer languages, a directory is used to store values in the form of lists. A directory is comparable to a file in many ways. The directory, like a file, may be used to conduct various activities. These activities are used to modify an existing directory or create a new one. The following procedures can be done on a directory: • Making a new directory. • Opening an existing directory. • Reading directory content. • Modifying a directory path. • Directory closing. • Delete a directory.

Fundamentals of Perl   ◾    65

Making a New Directory mkdir(PATH, MODE) is used to create a directory. This function assists in creating a new directory; if the user wishes to check whether the file already exists, the -e function can be used. PATH sets the path using the mode specified by the MODE function. Example: #!/usr/bin/perl # Directory Path my $directory = 'C:\Users\PeeksForPeeks\Folder\ Perl'; # Creating directory in perl mkdir($directory) or die "No $directory directory, $!"; print "Directory created \n";

Opening an Existing Directory In Perl, the short function opendir DIRHANDLE, PATH is used to open a directory. The PATH parameter defines the path to the directory to be opened. Example: #!/usr/bin/perl my $directory = 'C:\Users\PeeksForPeeks\Folder'; opendir (DIR, $directory) or die "No directory, $!"; while ($file = readdir DIR) { print "$file\n"; } closedir DIR;

Read Directory in the Scalar and List Context Reading a directory is a regular operation since one must read what is stored in the files every time the code is run or understood. readdir DIRHANDLE is used to read a directory. A user can read the directory in two ways: list context and scalar context.

66   ◾    Mastering Perl

In the list context, the code returns all the remaining entries in the directory. If the entries in the directories are empty, the undefined values in the scalar context and the empty list in the list context are returned. Scalar context: #!/usr/bin/perl use strict; use warnings; use 5.010; # Directory Path my $directory = shift // 'C:\Users\GeeksForGeeks\ Folder'; # Opening directory opendir my $dh, $directory or die "Could not open '$directory' for the reading '$!'\n"; # Printing content of directory while (my $content = readdir $dh) { say $content; } # Closing directory closedir $dh;

List context: #!/usr/bin/perl use strict; use warnings; use 5.010; # Directory Path my $directory = shift // 'C:\Users\PeeksForPeeks\ Folder'; # Opening-directory opendir my $dh, $directory or die "Could not open '$directory' for the reading '$!'\n";

Fundamentals of Perl   ◾    67 # Reading content of file my @content = readdir $dh; # Printing content of the directory foreach my $content (@content) { say $content; } # Closing directory closedir $dh;

Modifying Directory Path The chdir() method is used to modify a directory. This function assists in changing the directory and sending it to a different place. When invoked with a script, the chdir() function changes the directory for the rest of the script. The directory on the terminal will not be updated if this function is called from within a script. However, when called directly with a new directory path, differences are displayed in the terminal at the same time. Example: When the function chdir() is used within a script: #!/usr/bin/perl # Module to return # the current directory path use Cwd; # Path of the new directory $directory = "C:/Users"; # Printing the path of the current directory # using cwd function print "Current directory is "; print(cwd); print "\n"; # Changing directory using the chdir function chdir($directory) or die "Couldn't go inside $directory directory, $!"; # Printing path of changed directory print "Directory has change to $directory\n"; print "Current directory is ";

68   ◾    Mastering Perl print(cwd); print "\n";

Directory Closing Closedir DIRHANDLE is used to shut a directory. DIRHANDLE is the handle of the directory that is opened using the opendir function. Example: #!/usr/bin/perl # Directory which is to be opened $dirname = "C:/Users/PeeksForPeeks"; # Opening directory # using opendir function opendir (dir, $dirname) || die "Error $dirname\n"; # Printing content of directory # using the readdir function while(($filename = readdir(dir))) { print("$filename\n"); } # Closing directory using closedir closedir(dir);

Delete a Directory The rmdir function can be used to remove a directory. This function removes the supplied directory by FILENAME only if it is empty; if successful, it returns true; otherwise, it returns false. Example: #!/usr/bin/perl $directory = "C:/Users/PeeksForPeeks/Folder/Perl"; # This removes the Perl directory rmdir($directory ) or die "Couldn't remove $directory directory, $!"; print "Directory-removed \n";

Fundamentals of Perl   ◾    69

In this chapter, we covered the fundamental of Perl, where we discussed modes of writing, Boolean values, operators, and variables. Furthermore, we covered modules in Perl, packages in Perl, numbers and their types, and directories with CRUD operations.

NOTES 1. Perl - Operators. 2. Perl | Variables.

Chapter

3

Input and Output in Perl

IN THIS CHAPTER

➢➢ Use of print() and say() ➢➢ print Operator ➢➢ Use of STDIN for Input In the previous chapter, we covered the Fundamental of Perl, and in this chapter, we will cover input and output with its relevant examples.

PERL print() AND say() METHODS Perl evaluates input provided by the user or presented as Hardcoded input in the code using statements and expressions. Because it has been evaluated in the compiler, this evaluated expression will not display to the programmer. Perl employs the print() and say() functions to display the evaluated expression. These routines can show whatever parameters are supplied to them. print() Operator The print() operator in Perl is used to print the values of expressions in a List supplied to it as an input. The print operator returns anything passed to it as an argument, whether it’s a string, a number, a variable, or anything else. This operator’s delimiter in double quotes (“”).

DOI: 10.1201/9781003358442-3

71

72   ◾    Mastering Perl

Syntax: print "";

Example: #!/usr/bin/perl -w # Defining string $string1 = "Peeks For Peeks"; $string2 = "Welcome all"; print "$string1"; print "$string2";

The above example uses the print function to print both strings, but they are written on the same line. To avoid this and print them on distinct lines, we must use the “\n” operator, which changes the line whenever it is used. Example: #!/usr/bin/perl -w # Defining a string $string1 = "Peeks For Peeks"; $string2 = "Welcome all"; print "$string1\n"; print "$string2";

If we use single quotes instead of the double quotes, the print() method will not output the values of the variables or the escape characters used in the statement, such as “\n”. These characters will be printed in their entirety and will not be evaluated. #!/usr/bin/perl -w # Defining string $string1 = 'Peeks For Peeks'; $string2 = 'Welcome all'; print '$string1\n'; print '$string2';

Input and Output in Perl   ◾    73

say() Function The say() method in Perl functions similarly to the print() function, with one minor difference: the say() function automatically inserts a newline at the end of the statement, removing the need to use the newline character “n” to change the line. Example: #!/usr/bin/perl -w use 5.010; # Defining string $string1 = "Peeks For Peeks"; $string2 = "Welcome all"; # say() function to print say("$string1"); say("$string2");

We used “use 5.010” to utilize the say() function since newer versions of Perl don’t support some of the earlier versions’ features; thus, the older version is used to run the say() method.

print OPERATOR In Perl, the print operator is used to print the values of expressions in a List that is passed to it as an argument. The print operator returns anything passed to it as an argument, whether it’s a string, a number, a variable, or anything else. This operator is delimiter by double quotes (“”). Syntax: print "" Returns: 0 on failure and 1 on success.

First example: #!/usr/bin/perl -w # Defining a string

74   ◾    Mastering Perl $string = "Geeks For Geeks"; # Defining an array of Integers @array = (20, 30, 40, 50, 60, 70); # Searching a pattern in string # using index() function $index = index ($string, 'or'); # Printing the position of the matched pattern print "Position of 'or' in string $index\n"; # Printing defined array print "Array of the Integers is @array\n";

Second example: #!/usr/bin/perl -w # Defining string $string = "Welcome to PFP"; # Defining an array of integers @array = (-20, 30, 25, -50, 55, -70); # Searching a pattern in string # using index() function $index = index($string, 'o P'); # Printing the position of the matched pattern print "Position of 'o P' in string $index\n"; # Printing the defined array print "Array of the Integers @array\n";

USE OF STDIN FOR INPUT Perl allows the programmer to receive user input and conduct actions on it. This allows the user to enter input other than the one provided by the programmer as Hardcoded input. The print() method can then be used to parse and print this input. can provide keyboard input to a Perl application. STDIN is an abbreviation for Standard Input. There is no need to include STDIN

Input and Output in Perl   ◾    75

between the “diamond” and “spaceship” operators, i.e. . This is standard procedure. The < > operator can also be used to write to files. can be used in both Scalar and List contexts. Syntax: $a = ; or $a = ;

Example: #!/usr/bin/perl -w use strict; use warnings; print"Enter text:"; my $string = ; print "We entered $string as a String";

After entering Input, the above code requires us to press ENTER. This ENTER instructs the compiler to run the following line of code. However, treats the ENTER key as part of the input and prints the line when we hit it. Following the Input string, a new line will be written automatically. To avoid this, the chomp() method is used. This method will delete the newline character placed at the end of the usersupplied Input. Example: #!/usr/bin/perl -w use strict; use warnings; print"Enter text:"; my $string = ; chomp $string; print "We entered $string as a String";

In this chapter, we covered the use of print() and say(), print operator, and STDIN for Input.

Chapter

4

Control Flow in Perl

IN THIS CHAPTER

➢➢ Decision-Making ➢➢ Loops ➢➢ when Statement ➢➢ goto Operator ➢➢ next Operator ➢➢ redo Operator In the previous chapter, we discussed input and output in Perl, and in this chapter, we will cover control flow statements.

DECISION-MAKING IN PERL Making decisions in programming is analogous to making decisions in real life. When a given condition is met in programming, a particular code block must be performed. Control statements are used in a programming language to control program execution flow based on particular criteria. These affect the execution flow to progress and branch based on changes in a program’s state. Perl decision-making statements: • if • if else DOI: 10.1201/9781003358442-4

77

78   ◾    Mastering Perl

• nested if • if elsif ladder • unless • unless else • unless elsif if Statement The if statement is similar to those seen in other programming languages. It is used to carry out simple condition-based tasks. It is used to determine whether a specific statement or block of statements will be executed; for example, if a given condition is true, then a block of statements is executed; otherwise, it is not. Syntax: if(condition) { # code executed }

There will be a build time error if curly brackets {} are not utilized with if statements. As a result, brackets {} must be used with the if statement.

Control Flow in Perl   ◾    79

Flowchart:

Statement of if.

Example: # program to illustrate the if statement $c = 10; # if condition to check # for the even number if($c % 2 == 0 ) { printf "Even-Number"; }

if else Statement If the condition is true, the if statement evaluates the code; if the condition is false, the else statement is used. It instructs the code on what to do if the condition is false.

80   ◾    Mastering Perl

Syntax: if(condition) { # if a condition is true } else { # if a condition is false }

Flowchart:

Statement of if else.

Control Flow in Perl   ◾    81

Example: # program to illustrate # if else statement $c = 21; # if condition to check # for the even number if($c % 2 == 0 ) { printf "Even-Number"; } else { printf "Odd-Number\n"; }

Nested if Statement Nested if is an if statement inside an if statement. In this situation, the if statement is the target of another if or else statement. Nested if can be used when more than one condition must be true and one of the conditions is a sub-condition of the parent condition. Syntax: if (condition1) { # Executes when the condition1 is true if (condition2) { # Executes when the condition2 is true } }

82   ◾    Mastering Perl

Flowchart:

Statement of nested if.

Example: # program to illustrate # the Nested if statement $c = 10; if($c % 2 ==0) { # Nested if statement # Will only executed # if above if statement # is true if($c % 5 == 0) {

Control Flow in Perl   ◾    83 printf "The Number is divisible by 2 and 5\n"; } }

if elsif else ladder Statement A user can select from a number of alternatives here. The if statements are performed in the order listed. When one of the if conditions is met, the statement associated with that condition is performed, and rest of the ladder is skipped. If none of the conditions are met, the last else expression is used.1 Syntax: if(condition1) { # If condition 1 is true, code will be executed. } elsif(condition2) { # code to be executed if the condition2 is true } elsif(condition3) { # code to be executed if the condition3 is true } .... else { # code to be executed if all conditions are false }

84   ◾    Mastering Perl

Flowchart:

Statement of if else if.

Example: # Perl program to illustrate # if - elseif ladder statement $c = 30; if($c == 20) { printf "c is 20\n"; } elsif($c == 25) { printf "c is 25\n"; }

Control Flow in Perl   ◾    85 elsif($c == 30) { printf "c is 30\n"; } else { printf "c is not present\n"; }

unless Statement If condition is false, the statements will execute. In a boolean context, the number 0, the empty string “”, the character “0”, the empty list (), and undef are all false, whereas all other values are true. Syntax: unless(boolean_expression) { # will execute if a given condition is false }

Flowchart:

Unless statement.

86   ◾    Mastering Perl

Example: # program to illustrate # unless statement $c = 20; unless($c != 20) { # if condition is false then # print following printf "c is not equal to 20\n"; }

unless else Statement When the boolean expression is true, the except statement is followed by an optional else statement. Syntax: unless(booleanexpression) { # execute if a given condition is false } else { # execute if a given condition is true }

Control Flow in Perl   ◾    87

Flowchart:

Unless else Statement.

Example: # program to illustrate # unless - else statement $c = 20; unless($c == 20) { # if condition is false then # print following printf "c is not equal to 20\n"; } else {

88   ◾    Mastering Perl # if condition is true then # print following printf "c is equal to 20\n"; }

unless elsif Statement The unless and an optional elsif can follow statement...else statement, which allows us to test many conditions with a single unless...elsif statement. Remember the following: Unless statements can have any number of elsifs, and all of them must appear before the else. Unless statements can have zero or one else’s, and they must appear after any elsif statements. When an elsif succeeds, none of the other elsif’s or elses are tried. Syntax: unless(boolean_expression 1) { # Executes when boolean expression 1 is false } elsif( boolean_expression 2) { # Executes when boolean expression 2 is true } else { # Executes when none of above condition is met }

Control Flow in Perl   ◾    89

Flowchart:

Statement of unless elsif.

Example: # program to illustrate # unless elsif statement $c = 70; unless($c == 80) { # if condition is false printf "c is not equal to 80\n"; } elsif($c == 80) { # if condition is true printf "c is equal to 80\n"; }

90   ◾    Mastering Perl else { # if none of condition matches printf "Value of c is $c\n"; }

LOOPS IN PERL In programming languages, looping is a feature that allows the execution of a collection of instructions or functions repeatedly while some condition is true. Loops make the job of the coder easier. Perl supports many forms of loops to handle conditional situations in programs. Perl’s loops are discussed below. for Loop The “for” loop is a shorthand means of expressing the loop structure. Unlike a while loop, a for statement consumes the setup, condition, and increment/decrement on a single line, resulting in a shorter, easier to debug looping structure. Syntax: for (init statement; condition; increment/ decrement ) { # Code Executed }

Control Flow in Perl   ◾    91

Flowchart:

for loop in Perl.

A for loop operates on a predefined control flow. The following factors influence control flow: • init statement: The init statement is the initial statement that is performed. In this stage, we set up a variable to control the loop. • condition: The specified condition is assessed in this stage, and the for loop is executed if it is True. Because the condition is verified before the loop statements are executed, it is also an entry control loop. • Statement execution: When the condition is true, the statements in the loop body are performed. • increment/decrement: The loop control variable is incremented or decremented here to update the variable for the next iteration. • Loop termination: When the condition is met, the loop terminates, indicating the end of its life cycle. Example: # program to illustrate # for loop

92   ◾    Mastering Perl # for loop for ($count = 1 ; $count = 0) { $count = $count - 1; print "PeeksForPeeks\n"; }

Infinite While Loop A while loop can continue indefinitely, which means it has no end condition. In other words, some circumstances remain true, causing the while loop to continue endlessly or never finish. Example: The following application will print the provided statement indefinitely and display the runtime error Output Limit Exceeded on the online IDE. # program to illustrate # infinite while loop # infinite while loop # containing condition 1 # which is always true while(1) { print "Infinite While Loop\n"; }

do...while loop The only difference between a do...while loop and a while loop is that the do...while loop is executed at least once. After the initial execution, the

94   ◾    Mastering Perl

condition is verified. When we want the loop to execute at least once, we use a do...while loop. Because the condition is verified after performing the loop, it is also known as an exit controlled loop. Syntax: do { # statements Executed } while(condition);

Example: # program to illustrate # do..while Loop $c = 20; # do..While loop do { print "$c "; $c = $c - 1; } while ($c > 0);

until Loop The inverse of the while loop is the until loop. It accepts a condition in the parenthesis and only runs until it is false. It essentially repeats an instruction or sequence of instructions until the condition is FALSE. It is also an entry controller loop, which means that the condition is tested first, and then a sequence of instructions within a block is executed. Syntax: until (condition) { # Statements executed }

Control Flow in Perl   ◾    95

Example: # program to illustrate until Loop $c = 20; # until loop until ($c < 1) { print "$c "; $c = $c - 1; }

Nested Loops A nested loop is a loop that is contained within another loop. Perl programming also supports nested loops. All of the loops listed above can also be nested. Perl syntax for several nested loops: • Nested for loop for (init statement; condition; increment/ decrement ) { for (init statement; condition; increment/ decrement ) { # Code Executed } }

• Nested foreach loop foreach variable_1 (@array_1) { foreach variable_2 (@array_2) { # Code Executed } }

96   ◾    Mastering Perl

• Nested while loop while (condition) { while (condition) { # Code Executed } }

• Nested do...while loop do{ do{ # Code Executed }while(condition); }while(condition);

• Nested until loop until (condition) { until (condition) { # Code Executed } }

Example: # program to illustrate # nested while Loop $c = 5; $d = 0; # outer while loop while ($c < 7) { $d = 0; # inner while loop while ( $d ” “+” “+>>”

The Read Only Mode Creates file (if necessary), Clears contents of the File and Writes to it Creates file (if necessary), Appends to File Reads and Writes but does NOT Create Creates file (if necessary), the Clears, Reads and Writes Creates file (if necessary), the Reads and Appends

Example: Consider the file Hello1.txt, which initially contains the text “Welcome to PeeksForPeeks!!”. 1. Mode = “” This is the read-only mode. The original contents are erased when we open a file in this mode. If no file with the same name is found, it creates one. #!/usr/bin/perl # Opening File Hello1.txt in Read mode open(r, "", "Hello1.txt"); # Set r to the beginning of Hello1.txt seek r, 0, 0; print "\nWriting to the File..."; # Writing to Hello1.txt using print print w "The Content of this file is changed"; # Closing FileHandle close(w); # Set r to beginning of Hello1.txt seek r, 0, 0; # Print the current contents of Hello1.txt print("\nUpdated Content of Hello1.txt: ".); # Close FileHandle close(r);

3. Mode=“>>” Append mode is active. The original content is not deleted when we open a file in this mode. Because the string always attaches at the

File Handling in Perl   ◾    113

end, this mode cannot be used to overwrite. If no file with the same name is discovered, it creates one. #!/usr/bin/perl # Opening File Hello1.txt in Read mode open(r, ">", "Hello1.txt"); # Set r to beginning of Hello1.txt seek r, 0, 0; print "\nAppending to the File..."; # Appending to Hello1.txt using print print A " Hello Everyone!"; # close FileHandle close(A); # Set r to the beginning of Hello1.txt seek r, 0, 0; # Print current contents of Hello1.txt print("\nUpdated Content of Hello1.txt: ".); # Close FileHandle close(r);

4. Mode = “+” This is known as Read-Write mode. The distinction between “+” and “+>” is that “+>” can create a new file even if one with the same name already exists, whereas “+” cannot. #!/usr/bin/perl # Opening File Hello1.txt in the Read mode open(r, "", "Hello1.txt"); # Original contents of File # are cleared when File is opened print("\nContents of Hello1.txt gets cleared…"); # The string is written to File print rw "Hello!!! This is the updated file.";

File Handling in Perl   ◾    115 # Set rw to the beginning of File for reading. seek rw, 0, 0; print("\nUpdated Content of Hello1.txt: " .); # Closing File close(rw);

6. Mode = “+>>” This is called Read-Append mode. This may be used to both read from and append to a file. A new one with the same name is generated if no such file exists. # Open Hello1.txt in Read-Append Mode open(ra, "+>>", "Hello1.txt"); # Set ra to beginning of File for reading. seek ra, 0, 0; # Original content of File # is NOT cleared when File is opened print("Existing Content of File: ". ); print "\nAppending to File...."; # The string is appended to File print ra "Added using Read-Append Mode"; # Set ra to the beginning of File for reading. seek ra, 0, 0; # Printing updated content print("\nUpdated content of File: ".

);

# Closing File close(rw);

Redirecting Output Using the choose function, output may be redirected away from the console and into a file.

116   ◾    Mastering Perl

Syntax: select FileHandle; Parameters: FileHandle – FileHandle of File to be selected.

Steps: • To write, open a FileHandle and type “>”, “>>”, “+”, or “+>>”. • Using the select function, choose the FileHandle. Anything printed using the print function is now redirected to the file. Example: # Open a FileHandle in Write Mode. open(File, ">", "Hello1.txt"); # This sets File as default FileHandle select File; # Writes to File print("This goes to File."); # Writes to File print File "\nThis goes to File too."; # This sets STDOUT as default FileHandle select STDOUT; print("This goes to console."); # Close FileHandle. close(File);

FILE OPENING AND READING A FileHandle is a Perl internal structure that connects a physical file to a name. All FileHandles have read/write access; therefore, reading/writing is possible once attached to a file. However, when associating a FileHandle, the mode in which the file handle is opened must give.

File Handling in Perl   ◾    117

Opening a File The Open function is used to open either a new or existing file. Syntax: open FILEHANDLE, VAR

In this case, FileHandle is the handle returned by the open function, and VAR is the expression containing the file name and opening mode. The table below displays the various file opening modes and access to various operations. Mode

Description

r or < w or > a or >> r+ or +< w+ or +> a+ or +>>

The Read Only Access Creates, Writes, and Truncates Writes, Appends, and Creates Reads and Writes The Reads, Writes, Creates, and Truncates The Reads, Writes, Appends, and Creates

Reading a File When a FileHandle is assigned to a file, it may perform actions such as reading, writing, and appending. There are several methods for reading the file. • Making use of a FileHandle operator • Utilizing the getc function • Utilizing the read function FileHandle Operator The most common way to read data from an open FileHandle is with the operator < >. When used in a list context, the < > operator returns a list of lines from the provided FileHandle. The following example reads one line from a file and puts it in a scalar. Let the contents of the file “PFP.txt” be as follows: PeeksforPeeks Hello Peek Peek a revolution Peeks are the best

118   ◾    Mastering Perl

Example: # Opening file open(fh, "PFP.txt") or die "File '$filename' can't open"; # Reading First line from file $firstline = ; print "$firstline\n";

getc Function The getc function retrieves a single character from the FileHandle given, or STDIN if none is specified.

Syntax: getc FILEHANDLE

Example: # Opening file open(fh, "PFP.txt") or die "File '$filename' can't opene"; # Reading First char from file $firstchar = getc(fh); print "$firstchar\n";

If an error occurs or the FileHandle is at the end of the file, it returns undef. read Function The read function reads binary data from a file using the FileHandle.

Syntax: read FILEHANDLE, SCALAR, LENGTH, OFFSET read FILEHANDLE, SCALAR, LENGTH

If no OFFSET is supplied, LENGTH denotes the length of data to be read, and the data is inserted at the beginning of SCALAR. Otherwise, data is inserted after OFFSET bytes in SCALAR. If the file reading succeeds,

File Handling in Perl   ◾    119

the function returns the number of bytes read, zero at the end of the file, or undef if an error occurred. Reading More than One Line at a Time The following example reads the file’s contents indicated by FileHandle until it hits the end of file (EOF). Example: # Opening the file open(FH, "PFP.txt")or die "Sorry, couldn't open"; print "Reading the file \n"; # Reading file till FH reaches EOF while() { # Printing one line at a time print $_; } close;

Exception Handling in Files The exception can be handled in one of the two ways: • If the file cannot open, throw an exception. • If the file cannot open, issue a warning and continue operating. Throw an Exception When FileHandle is not allocated a valid file pointer, a die is run, which prints the message and terminates the current program.

Example: # Initializing filename $filename = 'PFP1.txt'; # Prints an error and exits if the file not found open(fh, '', "file_name.txt");

If the file already exists, it replaces the old content with the new content. Otherwise, a new file will generate with fresh content. print() Function The print() method is used to write data to a file. Syntax: print the filehandle string

When the file is opened, the FileHandle is associated with it, and the string contains the content to be written to the file.

File Handling in Perl   ◾    121

Example: # Opening file Hello1.txt in write mode open (fh, ">", "Hello1.txt"); # Getting the string to be written # to the file from the user print "Enter the content to add\n"; $a = ; # Writing to file print fh $a; # Closing the file close(fh) or "Couldn't close file";

The program operates as follows: • Step 1: Open the Hello.txt file in write mode. • Step 2: Extract text from the standard input keyboard. • Step 3: Save the string saved in “$a” to the file indicated by the FileHandle “fh”. • Step 4: Save the file. The following example reads the source file’s content and writes it to the destination file: # Source-File $src = 'Source.txt'; # Destination File $des = 'Destination.txt'; # open the source file for reading open(FHR, '', $des); print("Copying the content from $src to $des\n");

122   ◾    Mastering Perl while() { print FHW $_; } # Closing filehandles close(FHR); close(FHW); print "File content copied successfully!\n";

The program operates as follows: • Step 1: Read the file Source.txt and write the file Destination.txt. • Step 2: Reading content from the FHR, which is a FileHandle for reading content and a FileHandle for writing content to a file. • Step 3: Using the print function, copy the content. • Step 4: Once file has been read, close the conn. Error Handling and Error Reporting Errors can be handled in one of the two ways: • If the file cannot open, throw an exception (handling an error). • If the file cannot open, issue a warning and continue operating (error reporting). Throw an Exception (Using Die Function) When FileHandle is not allocated a valid file pointer, a die is run, which prints the message and terminates the current program.

Example: # Initializing filename $filename = 'Hello1.txt'; # $filename = 'ello1.txt'; # Prints error and exits # if file not found open(fh, '>", "Hello.txt") or die "File couldn't be opened"; # Getting the text to be appended # from the user print "\n\nEnter the text to append\n"; $a = ; # Appending content to file print FH $a; # Printing the success message print "\nAppending to File is Successful.\n"; # Reading the file after appending print "\nAfter the appending, Updated File is\n"; # Opening file in the read mode to # display updated content open(FH, "Hello1.txt") or die "Sorry, couldn't open"; while() { print $_; } close FH or "couldn't close";

The program operates as follows: • Step 1: Open a file in read mode to view the file’s existing content. • Step 2: Print the file’s existing content.

File Handling in Perl   ◾    125

• Step 3: Add material to the file by opening it in Append mode. • Step 4: Collect user text to attach to a file. • Step 5: Add text to the file. • Step 6: Re-read the file to determine if the content has been changed. • Step 7: File closure.

CSV FILE READING Perl was originally intended for text processing, such as extracting information from a text file and converting it to a new format. In Perl, reading a text file is a pretty frequent activity. For example, reading CSV (commaseparated value) files to extract data and information is a common task. A CSV file can be created using any text editor, such as notepad, notepad++, or others. After adding material to a notepad text file, save it as a CSV file with the .csv extension. A CSV file example:

CSV file example.

A CSV file can be used to handle database record files for an enterprise or organization. These files can be opened with ease in Excel and can be edited with any compatible application. Perl also enables the processing and construction of these “csv” files by extracting values from the file, modifying these values, and inserting the modified values back into the file. We will use the split function to extract every value from a particular line. Use of Split() for Data Extraction split() is a standard Perl function used to divide a string into sections using a delimiter. This delimiter can be any character specified by the user; however, we usually use a comma. split() accepts two arguments. The first is a delimiter, and the second is the string to be divided.

126   ◾    Mastering Perl

Syntax: split(_delimiter_, _string_); Parameter: _delimiter_ : Separator value between the elements _string_: From which values are to extract Returns: Array of string elements separated by _delimiter_

Example: Input: $s = "Shona loves Sugar" Output: "Shona", "loves", "Sugar" If Input string is passed to split function as, @words = split("", $s); The array @words will fill with 3 values: "Shona", "loves" and "Sugar".

The following procedures are used to divide lines in a CSV file into sections using a delimiter: • Step 1: Read file line by line. • Step 2: Put all the values from each line into an array. • Step 3: To obtain the result, print out all the data individually. Let’s look at an example to grasp the subject better. The split() method is used to divide the strings recorded in the new.csv file using a delimiter, as seen below: use strict; my $file = $ARGV[0] or die; open(my $data, ' prompt, type and execute the “q” command. read_file function in the Slurp: The read file function of File::Slurp reads the complete contents of a file with the file name and returns it as a string. However, File::Slurp is recommended since it has a few encoding layer flaws that may cause compilation difficulties. File::Slurper seeks to offer a viable answer to the difficulties above. Syntax: use File::Slurp; my $text = read_file($file_name); Return: It returns a string.

read_text function in the Slurp: The read_text method in File::Slurper accepts an optional encoding parameter (if any) and can automatically decode CRLF line ends if we request it (for Windows files). Syntax: use File::Slurper; my $content = read_text($file_name); Return: It returns string.

Note: CRLF line endings indicate a line break in a text file (Windows line break types). Slurp’s write_file function: The File::Slurp module’s write_file method is used to write to many files at once. It writes to file using a scalar variable containing the content of another file read by the read_file function.

138   ◾    Mastering Perl

Syntax: use File::Slurp; write_file($file_name, $content); Returns: It does not return any value, just writes content to the file.

First example: Storing file content using scalar # Perl code to illustrate slurp function use File::Slurp; # read whole file into a scalar my $content = read_file('C:\Users\PeeksForPeeks\PFP_ Slurp.txt'); # write out a whole file from scalar write_file('C:\Users\PeeksForPeeks\Copyof_PFP_Slurp. txt', $content);

Explanation: In the preceding Perl code, we used a slurp function to read a file named PFP_Slurp.txt containing several lines of text as input into a scalar variable named $content and then wrote the contents of the file as a single string into another file Copyof_PFP_Slurp.txt. Second example: Storing file content in an array # perl code to illustrate slurp function use File::Slurp; # read whole file into a scalar my @lines = read_file('C:\Users\PeeksForPeeks\PFP_ Slurp2.txt'); # write out a whole file from scalar write_file('C:\Users\PeeksForPeeks\Copyof_PFP_Slurp2. txt', @lines);

Explanation: In the preceding Perl code, we used a slurp function to read a file named PFP_Slurp2.txt containing an array of lines of text as input into an array variable named @lines and then wrote the contents of the whole file as a single string into a file named Copyof PFP_Slurp2.txt.

File Handling in Perl   ◾    139

Third example: Writing a function that use the slurp technique # Perl code to illustrate the slurp function use strict; use warnings; use File::Slurp; # calling user defined function get_a_string(); sub get_a_string { # read entire file into a scalar my $pfp_str = read_file('C:\Users\PeeksForPeeks\PFP_ User_Slurp.txt'); # write entire file from scalar write_file('C:\Users\PeeksForPeeks\Copyof_PFP_User_ Slurp.txt', $pfp_str); }

Explanation: In the above Perl code, strict and warnings allow the user to enter code more freely and catch errors such as typos in variable names earlier. We invoked a user-defined function named get_a_string, which then performs the slurp function, which reads a file containing some lines of text as input into a variable named pfp_str and then wrote the contents of the entire file as a single string into a file.

USEFUL FILE-HANDLING FUNCTIONS Perl was initially developed for text processing, such as extracting information from a text file and converting the text file into a new format. These procedures can be carried out using a variety of built-in file functions. Example: #!/usr/bin/perl # Opening File in Read-only mode open(fh, "{_StudentLastName}\n"; bless $self, $class; return $self; }

A function called bless is used in the preceding example code. This function is used to associate an object with a class passed as an argument. Syntax: bless Objectname, ClassName

Creating an Object In Perl, an object is created by calling the constructor defined in the class. An object name can be any variable the user requires, but it is customary to name it in relation to the class. $Data = Student_data student( "Diksha", "Mayank");

Example: use strict; use warnings; package student; # constructor sub student_data { # shift will take package name 'student' # and assign it to the variable 'class'

184   ◾    Mastering Perl my $class_name = shift; my $self = { 'StudentFirstName' => shift, 'StudentLastName' => shift }; # Using the bless function bless $self, $class_name; # returning object from the constructor return $self; } # Object creation and constructor calling my $Data = new student_data student("Geeks", "forGeeks"); # Printing the data print "$Data->{'StudentFirstName'}\n"; print "$Data->{'StudentLastName'}\n";

Using classes in OOP is critical because it precisely depicts real-world applications and can be used to solve real-world problems.

OBJECTS IN OOPs Perl is an object-oriented, interpreter-based, dynamic programming language. OOP has three primary components: objects, classes, and methods. An object is a data type that may be referred to as an instance of the class it belongs. It may be a collection of data variables of various data kinds and a collection of various data structures. Methods are functions that operate on class object instances. The following example illustrates how objects may use in Perl: We must first define the class. In Perl, this is accomplished by constructing the class’ package. A package is an encapsulated object that contains all of the class’ data members and functions. package Employee;

Employee is the class name in this case. The second task is to create a package instance (i.e., the object). We’ll need a constructor for this. In Perl, a constructor is a subroutine that is usually called “new.” However, because the name is user-defined, it is not limited to “new.”

Object-Oriented Programming in Perl   ◾    185 package Employee; # Constructor with the name new sub new { my $class = shift; my $self = { _serialNum => shift, _firstName => shift, _lastName => shift, }; bless $self, $class; return $self; }

To design our object, we define a basic hash reference $self in the constructor. Here, the object will contain three properties for an Employee: serialNum, firstName, and lastName. This indicates that each employee will have their serial number, firstname, and lastname. The my keyword functions as an access specifier that localizes $class and $self to the contained block. The shift keyword transfers the package name from the default array “@_” to the bless function. The bless method returns a reference that eventually becomes an object. And lastly, the constructor will return an instance of the Employee class. The most important aspect is how to initialize an object. It may be accomplished as follows: $object = new Employee(1, "Peeks", "forPeeks");

In this case, $object is a scalar variable that refers to the hash defined in the constructor. The following is an example program for creating and implementing objects in OOPs: use strict; use warnings; # class with the name Employee package Employee; # constructor with name new sub new

186   ◾    Mastering Perl { # shift will take package name # and assign it to the variable 'class' my $class = shift; # defining hash reference my $self = { _serialNum => shift, _firstName => shift, _lastName => shift, }; # Attaching object with the class bless $self, $class; # returning the instance of class Employee return $self; } # Object creation of class my $object = new Employee(1, "Peeks", "forPeeks"); # object here is a hash to reference print("$object->{_firstName} \n"); print("$object->{_serialNum} \n");

An object in Perl functions in the same way that it does in other languages, such as C++ and Java. The above program demonstrates the procedure of an object in Perl, including its creation and use in a class.

METHODS IN OOPs Methods are used to access and alter an object’s data. These are the entities that may be called via class or package objects. Methods in Perl are just subroutines; they have no unique identity. A method’s syntax is identical to that of a subroutine. Methods, like subroutines, are specified using the sub keyword. As its first parameter, the method accepts an object or the package on which it is called. OOPs employ these methods to change the object’s data and not to interact with the object directly; this is done to ensure the data’s security by preventing the programmer from directly altering the object’s data.

Object-Oriented Programming in Perl   ◾    187

Various helper methods that accept the object as an argument and save its value in another variable make this possible. Additionally, adjustments are made to the second variable. These changes do not affect the object’s data, making it more secure. Types of Methods in Perl Based on the inputs given, methods in Perl may be divided into two categories: static and virtual methods. A static method is one where the method’s first parameter is the class name. The functionality of a static method is applied to the whole class since it accepts the class’ name as an argument. These are also known as class methods. Since most methods belong to the same class, it is unnecessary to supply the class name as an argument. Example: A class’ constructors are considered static methods. Virtual method is one in which the object reference is supplied as the function’s first parameter. The first parameter of a virtual function is relocated to a local variable and then utilized as a reference. Example: sub Student_data { my $self = shift; # Calculating-result my $result = $self->{'Marks_obtained'} / $self->{'Total_marks'}; print "Marks scored by student are: $result"; }

In OOP, methods require parentheses to hold the arguments, and these methods are invoked with an arrow operator (->). get-set Methods Methods are used to secure an object’s data and are thus used with either the object’s reference or the value is stored in another variable and then used. In OOPs, get-set methods are used to provide data security to objects. The get-method is used to retrieve the object’s current value, while the set value method assigns a new value to the object.

188   ◾    Mastering Perl

Example: # Declaration and definition of the Base class use strict; use warnings; # Creation of parent class package vehicle; # Setter method sub set_mileage { # shift will take package name 'vehicle' # and assign it to the variable 'class' my $class = shift; my $self = { 'distance'=> shift, 'petrol_consumed'=> shift }; # Bless function to bind the object to the class bless $self, $class; # returning object from the constructor return $self; } # Getter-method sub get_mileage { my $self = shift; # Calculating0result my $result = $self->{'distance'} / $self->{'petrol_consumed'}; print "The mileage by our vehicle is: $result\n"; }

Object-Oriented Programming in Perl   ◾    189 # The Object creation and method calling my $ob1 = vehicle -> set_mileage(2550, 170); $ob1->get_mileage();

CONSTRUCTORS AND DESTRUCTORS We will explain constructors and destructors with examples. Constructors Constructors in Perl subroutines return an instance of the class as the returned object. In Perl, the constructor is usually referred to as “new.” Unlike many other OOP languages, Perl has no particular syntax for object construction. It utilizes data structures (hashes, arrays, scalars) that have been expressly connected with the class. On hash reference and the class name, the constructor calls the “bless” method (the name of the package).1 Let’s develop some programs for better explanations. Note: Due to the use of packages, the following code will not execute on online IDE. The following text represents a Perl class or module file. Save the file with the extension (*.pm). # Declaring Package package Area; # Declaring Constructor method sub new { return bless {}, shift; # blessing on hashed # reference (which is empty). } 1;

The package name “Area” is stored in default array “@_” when the constructor method is called. The keyword “shift” is used to extract the package name from “@_” and pass it to the “bless” function. package Area; sub new { my $class = shift; # defining shift in the $myclass

190   ◾    Mastering Perl my $self = {}; # hashed reference return bless $self, $class; } 1;

In Perl, attributes are stored as key-value pairs in a hashed reference. Additionally, some attributes are being added to the code. package Area; sub new { my $class = shift; my $self = { length => 3, # storing-length width => 4, # storing=width }; return bless $self, $class; } 1;

The (Area Class) code above has two attributes: length and width. Another Perl program is designed to use these attributes to gain access to them. use use use use

strict; warnings; Area; feature qw/say/;

# creating new Area object my $area = Area->new; say $area->{length}; #print length say $area->{width}; # print width

How to run the code: • Save the Program with Package Area as Area.pm in a text file. • Note: The file’s name should always be the same as the package’s name.

Object-Oriented Programming in Perl   ◾    191

• Save the program that is used to access the attributes defined in the package as *.pl. * can be any name here (In this case, it is test.pl). • Use the command perl test.pl to run the code saved as test.pl in the Perl command line. Passing Dynamic Attributes Adding Dynamic attributes to existing files: Program: Areas.pm package Area; sub new { my ($class, $args) = @_; # since values will be # passed dynamically my $self = { length => $args->{length} || 1, # by default value is 1 (stored) width => $args->{width} || 1, # by default value is 1 (stored) }; return bless $self, $class; } # we have added get_area function to # calculate area as well sub get_area { my $self = shift; # getting area by multiplication my $area = $self->{length} * $self->{width}; return $area; } 1;

Program: test.pl use strict; use warnings;

192   ◾    Mastering Perl use feature qw/say/; use Area; # pass length and width arguments # to constructor my $area = Area->new( { length => 2, # passing '2' as param of the length width => 2, # passing '2' as param of the width }); say $area->get_area;

Destructors When all references to object are removed from scope, Perl automatically calls the destructor method. Destructor methods are useful if the class generates threads or temporary files that must be removed when the object is destroyed. Perl has a special method name for the destructor, “DESTROY,” which must be used when declaring the destructor. Syntax: sub DESTROY { # DEFINE-Destructors my $self = shift; print "Constructor-Destroyed :P"; }

METHOD OVERRIDING IN OOPs Overriding is a feature of any object-oriented computer language that allows a subclass or child class to implement a method that already exists in one of its superclasses or parents. When a subclass method has the same name, arguments or signature, and return type (or sub-type) as a method in its superclass, the subclass method is said to override the superclass method. Method overriding signifies that the code consists of two or more methods with the same name, each of which has unique purpose and differs from the others. Thus, the literal definition of the term indicates that one

Object-Oriented Programming in Perl   ◾    193

approach must take precedence over another. This idea refers to redefining a base class method in a derived class with the same method signature. Method overriding is one manner in which Runtime Polymorphism is achieved in Perl. The version of a method that is run is dependent upon the object that invokes it. If object of the parent class is used to call the method, the version in the parent class will run; however, if an object of the subclass is used, the version in the child class will execute. In other words, the type of the object being referenced decides which version of an overridden method will be performed, not the type of the reference variable. Method overriding in Perl is best shown with the following example. We have a base class vehicle that has the methods get_mileage() and get_cost(), as well as a derived class car that has the methods get_mileage() and get_age(). Now, because one of the methods in both classes has the same name, their execution will follow the Method overriding concept. Let’s look at the example and see how it’s performed. Base class creation: # Declaration and definition of the Base class use strict; use warnings; # Creating parent-class package vehicle; sub new { # shift will take package name 'vehicle' # and assign it to the variable 'class' my $class = shift; my $self = { 'distance'=> shift, 'petrol_consumed'=> shift }; # Bless function to bind object to class bless $self, $class; # returning object from the constructor return $self; }

194   ◾    Mastering Perl # Method for the calculating the mileage sub get_mileage { my $self = shift; # Calculating-result my $result = $self->{'distance'} / $self->{'petrol_consumed'}; print "The mileage by our vehicle is: $result\n"; } # Method for the calculating the cost sub get_cost { my $self = shift; # Calculating-result my $result = $self->{'petrol consumed'} * 70; print "Cost is: $result\n"; } 1;

Derived class creation: # Declaring and defining the derived class # Creating derived-class package car; use strict; use warnings; # Using the parent class use parent 'vehicle'; # Overriding method sub get_mileage { my $self = shift;

Object-Oriented Programming in Perl   ◾    195 # Calculating result my $result = $self->{'distance'} / $self->{'petrol_consumed'}; print "The mileage by our car is: $result"; } # Function to get age from the user sub get_age { my $self = shift; # Taking input from the user my $age = ; # Printing the age print "The Age is: $age\n"; } 1;

Using objects to demonstrate the Method Overriding process: # Calling objects and # methods of each class # using corresponding objects. use strict; use warnings; # Using derived class as parent use car; # the object creation and initialization my $ob1 = vehicle -> new(2550, 170); my $ob2 = car -> new(2500, 250); # Calling methods using the Overriding $ob1->get_mileage(); $ob2->get_mileage();

As can be seen, the method from the class that is being called with the object overrides the other method with the same name but in different

196   ◾    Mastering Perl

classes. The “get_mileage” method on the object vehicle prints “The mileage by our vehicle is: 15” via the method declared in the class vehicle. When we execute the method in the class car “get_mileage” on the object of car, we get the output “The mileage by our car is: 10.” Why Do We Override Methods? As noted before, overridden methods enable Perl to offer polymorphism at runtime. Polymorphism is crucial to OOP for the following reason: it enables a base class to describe methods that will share by all of its descendants, while subclasses may define the particular implementation of any or all of those methods. Perl also provides the “one interface, several methods” element of polymorphism through overridden methods. Dynamic method dispatch (runtime polymorphism) is one of objectoriented architecture’s most effective strategies for code reuse and resilience. The ability to exist code libraries to call methods on instances of new classes without recompilation while preserving a clean abstract interface is a potent instrument. Overridden methods enable us to invoke methods of any derived class without knowing the object type of the derived class. Thus, method overriding simplifies programming since there is no need to memorize distinct names when developing new methods; instead, it is more necessary to remember the processes inside the Method.

INHERITANCE IN OOPs Inheritance is a class’ ability to extract and use the characteristics of another class. It is the process of creating new classes, known as Derived classes, from existing classes, known as Base classes. The essential idea is that the programmer may utilize the characteristics of one class in another without declaring or defining the same item several times across classes. We may inherit the member functions from the base class instead of writing them in each class declaration. Inheritance is one of OOP’s most essential features. Subclass: A subclass or Derived class is a class that inherits properties from another class. Superclass: The class whose attributes are inherited by subclasses is known as the Superclass or Base Class. The most basic principle of inheritance is the creation or derivation of a new class from another class.

Object-Oriented Programming in Perl   ◾    197

Base Class and Derived Class Derived classes are created by deriving additional inherited subclasses from the base class. A single base class can have multiple derived classes; this type of inheritance is known as Hierarchical Inheritance. These derived classes are all derived from a single Parent or Base class. Multiple Inheritance occurs when a derived class shares multiple parent classes and inherits its features from multiple parent classes.

Base class and Drive class.

The image above depicts the order in which a class is derived from a base class. The order and denotations shown in the above image will be used whenever necessary to theoretically depict the order of inheritance. Consider the Vehicles class. Now we must create a class for each type of vehicle, such as a bus, car, or truck. For all Vehicles, the methods fuelAmount(), capacity(), and applyBrakes() will be the same.

Inheritance creation.

The preceding image depicts the creation of these classes without the concept of inheritance. The above process clearly results in the duplication of the same code three times. This raises the likelihood of error and data redundancy.

198   ◾    Mastering Perl

Inheritance is used to avoid situations like this. We can simply avoid data duplication and increase reusability if we create a class Vehicle, write these three functions in it, and inherit the rest of the classes from it. Analyze the diagram below to see how the three classes are derived from the vehicle class:

Three classes inherit from vehicle class.

Because we inherited the rest of the three classes from the base class, we only need to write the functions once instead of three times (Vehicle). Multilevel Inheritance In Perl, inheritance can take many forms, but the most common is Multilevel Inheritance, which involves a chain of base and derived classes. In Multilevel Inheritance, a derived class inherits a base class, and the derived class also serves as the base class for other classes. In the diagram below, class A serves as a base class for the derived class B, which serves as base class for the derived class C.

Multilevel Inheritance

Object-Oriented Programming in Perl   ◾    199

Implementing Inheritance in the Perl Packages can be used to implement inheritance in Perl. Packages are used to create a parent class from which derived classes can inherit functionality. use strict; use warnings; # Creating parent-class package Employee; # Creating-constructor sub new { # shift will take package name 'employee' # and assign it to the variable 'class' my $class = shift; my $self = { 'name' => shift, 'employee_id' => shift }; # Bless function to bind object to the class bless $self, $class; # returning object from the constructor return $self; } 1;

The base class is defined in the code above. The base class is employee, and the data members are the employee id and the employee’s name. This parent class code must be saved as *.pm, which we will do here as employee. pm. We’ll now look at how to create a class from the previously declared base class employee. # Creation of parent class package Department; use strict; use warnings;

200   ◾    Mastering Perl # Using the class employee as parent use parent 'employee'; 1;

As seen in the preceding example, the class Department makes use of the traits of the previously declared class employee. As a result, when we declared the class Department, we did not declare all of the data members again but instead inherited them from the base class employee. To run this code, save the intermediatory class code as *.pm, as Department.pm in this case. This is the intermediary class and will also serve as the parent class for the following derived file data .pl. use strict; use warnings; # Using the Department class as parent use Department; # Creating object and assigning the values my $a = Department->new("Rajat",18017); # Printing required fields print "$a->{'name'}\n"; print "$a->{'employee_id'}\n";

Thus, inheritance is significant when working on a large project and the programmer wants to shorten the code.

POLYMORPHISM IN OOPs Polymorphism is the capability of processing data in several forms. Poly means numerous, and morphism implies kinds; therefore, the term itself shows the meaning. Polymorphism is one of the most fundamental concepts of an OOP language. In OOP, polymorphism is often employed when a parent class reference refers to a child class object. This section will examine how to express any function in several kinds and formats. A real-world example of polymorphism is that a person may simultaneously play multiple roles in life. As a woman simultaneously fulfills the roles of mother, wife, employee, and daughter. Therefore, a single individual must possess various characteristics, each of which must be

Object-Oriented Programming in Perl   ◾    201

implemented according to the scenario and conditions. Polymorphism is regarded as one of the OOP’s most essential characteristics. OOP’s primary advantage is polymorphism. Polymorphism is so essential that languages that do not support it cannot call themselves objectoriented. Object-based languages are those that have classes but do not support polymorphism. Consequently, it is crucial for OOP language. It is the ability of an object or reference to take on multiple forms in different contexts. It supports function overloading, function overriding, and virtual functions.

Polymorphism in OOP.

Polymorphism is a property that allows any message to be sent to objects of multiple classes, and each object can respond appropriately based on the class properties. This means that in an OOP language, polymorphism is the method that does different things depending on the class of the object that calls it. $square->area(), for example, will return the area of a square, whereas $triangle->area() may return the area of a triangle. $object->area(), on the other hand, would have to calculate the area based on which class $object was called. Polymorphism is best explained by using the following example: use warnings; # Creation of class using package package A;

202   ◾    Mastering Perl # Constructor-creation sub new { # shift will take package name 'vehicle' # and assign it to the variable 'class' my $class = shift; my $self = { 'name' => shift, 'roll_no' => shift }; sub poly_example { print("This corresponds to a class A\n"); } }; package B; # The @ISA array contains a list # of that class's parent classes, if any my @ISA = (A); sub poly_example { print("This corresponds to a class B\n"); } package main; B->poly_example(); A->poly_example();

The method poly_example() defined in class B overrides the definition inherited from class A for the first output and vice versa for the second output. This allows you to add or extend the functionality of any pre-existing package without having to rewrite the entire definition of the class repeatedly. As a result, the programmer’s life is made more accessible.

Object-Oriented Programming in Perl   ◾    203

ENCAPSULATION IN OOPs Encapsulation in Perl is the process of enclosing data to secure it from external sources that should not have access to that section of code. Encapsulation is a component of OOP; it ties data to the subroutines that change it. Encapsulation is, in another sense, a protective barrier that prevents the data from being accessible by code outside of this shield. • Technically, under encapsulation, variables or data of a class are concealed from other classes and may only be accessible through member functions of the class in which they are defined. • As with encapsulation, the data inside a class is concealed from other classes; hence, it is sometimes referred to as data-hiding. • Encapsulation may be performed by declaring all class variables as local and retrieving class methods by importing packages to set and retrieve variable values.

Encapsulation in OOP.

Consider a real-world example of the encapsulation: in a business, there are several departments, such as accounts, finance, and sales. The finance sector conducts all financial transactions and maintains records of all financial data. Similarly, the sales department conducts all sales-related operations and maintains sales data. Now, there may be a situation in which a finance department official needs complete sales information for a given month. In this instance, he is not permitted direct access to the sales section’s data. He must first call another officer in the sales department and then request that individual data be provided. This describes encapsulation. Here, the sales section’s data and the people who may change them are grouped under the name “sales section.”

204   ◾    Mastering Perl

Example: # Declaration and definition of the Base class use strict; use warnings; package Student; sub new { # shift will take package name 'Student' # and assign it to the variable 'class' my $class = shift; my $self = { 'name'=> shift, 'age'=> shift, 'roll_no' => shift }; # Bless function to bind the object to class bless $self, $class; # returning object from the constructor return $self; } # Method for the displaying the details sub get_details { my $self = shift; print "The Name is: $self->{'name'}\n"; print "The Age is: $self->{'age'}\n"; print "The Roll_no is: $self->{'roll_no'}"; } # The Object creation and calling my $obj1 = Student->new("Rohini", 27, 15); $obj1->get_details();

If there is a need to access the class’ data for any modifications or simply to print the class’ data in the above code, it cannot be done directly. It is

Object-Oriented Programming in Perl   ◾    205

essential to create an object of that class and then use the get_details() method to access the data. This is referred to as Data Encapsulation. The benefits of encapsulation are: • Data-hiding: The user will be unsure of the inner implementation of the class. The user cannot see how the class stores data in its variables. They are just conscious that we are giving values to accessors, and variables are being initialized with those values. • Enhanced flexibility: We may make the class variables read-only or write-only depending on our needs. To make variables read-only, we need to utilize Get Accessor in the code. To make variables readonly, we must only utilize the Set Accessor. • Reusability: Encapsulation also promotes reusability and makes it simple to adapt to new needs. • Verifying code is simple: Encapsulated code is simple to unit test. This chapter covered OOP in Perl with classes and objects, methods, constructors, and destructors. Furthermore, we discussed method overriding, inheritance, polymorphism, and encapsulation.

NOTE 1. Perl | Constructors and Destructors.

Chapter

8

Subroutines in Perl

IN THIS CHAPTER

➢➢ Function Signature ➢➢ Passing Complex Parameters to a Subroutine ➢➢ Mutable and Immutable parameters ➢➢ Multiple Subroutines ➢➢ Use of return() Function ➢➢ Pass By Reference ➢➢ Recursion In the previous chapter, we discussed object-oriented programming in Perl, and in this chapter, we will cover subroutines.

SUBROUTINES OR FUNCTIONS A Perl function or subroutine is a collection of statements that execute a specific purpose. In any programming language, code reuse is desired. Therefore, the user places the chunk of code in a function or subroutine to eliminate the need to write code repeatedly. In Perl, the phrases function, subroutine, and method are synonymous, although they are distinct in other programming languages. The term subroutines is the most common in Perl programming since it is formed with the keyword sub. Whenever a function is called, Perl suspends the execution of the whole program, DOI: 10.1201/9781003358442-8

207

208   ◾    Mastering Perl

jumps to the function to execute it, and then returns to the previous area of code. One need not use the return statement. Determining Subroutines The general form of subroutine definition in Perl is as follows: sub subroutinename { # body of the method or subroutine }

Calling Subroutines Subroutines in Perl can invoke by passing the arguments list to it as follows: subroutinename(arugumentslist);

The method described above will only work with Perl versions 5.0 and later. There was another way to call the subroutine before Perl 5.0, but it is not recommended because it bypasses the subroutine prototypes. &subroutinename(arugumentslist);

Example: # Program to demonstrate # the subroutine declaration and calling #!/usr/bin/perl # defining-subroutine sub ask_user { print "Hello Everyone\n"; } # calling-subroutine # we can also use # &ask_user(); ask_user();

Passing Parameters to Subroutines This is used to pass values as arguments to subroutines. This is accomplished using the special list array variables “$_.” This will be assigned to the functions as $_[0], $_[1], etc.

Subroutines in Perl   ◾    209

Example: # Program to demonstrate # the Passing parameters to subroutines #!/usr/bin/perl # defining-subroutine sub area { # passing-argument $side = $_[0]; return ($side * $side); } # calling-function $totalArea = area(4); # displaying-result printf $totalArea;

Subroutines have the following advantages: • It allows us to reuse code and makes error detection and debugging easier. • It aids in the structural organization of the code. • Sections of code are organized in chunks. • It improves code readability. A Perl function or subroutine is a collection of statements that perform a specific task. Every programming language user wishes to reuse code. So the user puts the code section in a function or subroutine to avoid having to write the code repeatedly. We will go over the following ideas: • Hashes are passed to subroutines. • Lists are passed to subroutines. • Returning value from subroutine local and global variables. • Variable number of parameters in a subroutine call.

210   ◾    Mastering Perl

Passing Hashes to Subroutines A hash can also be passed to subroutines, which convert it to its key-value pair. Example: # Perl program to demonstrate the # passing of hash to subroutines #!/usr/bin/perl # Subroutine-definition sub Display_hash { # hash variable to store the # passed arguments my (%hash_var) = @_; # to display passed list elements foreach my $key (keys %hash_var ) { my $val = $hash_var{$key}; print "$key : $val\n"; } } # defining-hash %hash_para = ('Subject' => 'Perl Programing', 'Marks' => 69); # calling Subroutine with the hash parameter Display_hash(%hash_para);

Passing Lists to Subroutines Because @_ is a special array variable within a function or subroutine, it is used to pass lists to the subroutine. Perl accepts and parses arrays and lists differently, making it difficult to extract the discrete element from @_. To pass a list along with the other scalar arguments, the list must be passed as the last argument.

Subroutines in Perl   ◾    211

Example: # program to demonstrate # passing of lists to subroutines #!/usr/bin/perl # Subroutine-definition sub Display_List { # array variable to store the # passed arguments my @para_list = @_; # to print passed list elements print "Given list is @para_list\n"; } # passing the scalar argument $sc = 100; # passing-list @li = (20, 30, 40, 50); # Calling Subroutine with the scalar # and list parameter Display_List($sc, @li);

Returning a Value from a Subroutine A subroutine, like any other programming language, can return a value. If the user does not manually return a value from the subroutine, the subroutine will return a value automatically. In this case, the automatically returned value will result from the last calculation performed in the subroutine. The result can be a scalar, an array, or a hash. Example: # Program to demonstrate # the returning values subroutine #!/usr/bin/perl # subroutine-definition sub Sum {

212   ◾    Mastering Perl # To # of $num $s =

get total number the parameters passed. = scalar(@_); 0;

foreach $i (@_) { $s += $i; } # returning-sum return $s; } # subroutine calling and storing the result $result = Sum(40, 4, 50); # displaying the result print "Sum of given numbers : $result\n";

Local and Global Variables in Subroutines By default, all variables within a Perl program are global variables. However, using my keyword, you can create local or private variables within a block. A private variable has a limited scope, such as between blocks (if, while, for, foreach, and so on) and methods. These variables cannot be used outside of a block or method. Example: # program to demonstrate the Local # and Global variables in the subroutine #!/usr/bin/perl # Global variable $str = "PeeksforPeeks"; # subroutine-definition sub Peeks { # Private variable by using my # keyword for Peeks function my $str;

Subroutines in Perl   ◾    213 $str = "PFP"; print "Inside Subroutine: $str\n"; } # Calling-Subroutine Geeks(); print "Outside Subroutine: $str\n";

A Varying Number of Parameters in a Subroutine Call Perl does not include any built-in facilities for declaring the parameters of a subroutine, making it very simple to pass any number of parameters to a function. Example: # program to demonstrate the variable # number of parameters to the subroutine #!/usr/bin/perl use strict; use warnings; # defining-subroutine sub Multiplication { # private variable containing # the default value as 1 my $mul = 1; foreach my $val (@_) { $mul *= $val; }

return $mul; }

214   ◾    Mastering Perl # Calling the subroutine with 4 parameters print Multiplication(9, 4, 2, 5); print "\n"; # Calling subroutine again but # with the 3 parameters print Multiplication(4, 6, 3);

In general, passing more than one array or hash as a parameter to a subroutine causes it to lose its distinct identity. Likewise, returning more than one array or hash from a subroutine results in the loss of their distinct identities. We can solve these issues by making use of references.

FUNCTION SIGNATURE IN PERL A Perl function or subroutine is a collection of statements that perform a specific task. Every programming language user wishes to reuse code. So the user places the code section in a function or subroutine to avoid having to write the code repeatedly. Although the terms function, subroutine, and method are interchangeable in Perl, they are not in other programming languages. Because it is created with the keyword sub, the terms subroutines are commonly used in Perl programming. When a function is called, Perl stops executing its entire program and jumps to the function to execute it before returning to the section of code that was previously running. The return statement can be avoided. Defining Subroutines In Perl, the general form of defining a subroutine is as follows: sub subroutinename { # body of the method or subroutine }

Function Signature When a function is constructed, a set of parameters is also provided inside the parenthesis to specify the sort of arguments the function will receive on its call. This function signature may include one or several arguments.

Subroutines in Perl   ◾    215

A subroutine or function with a defined signature can only accept arguments of the type specified in its signature. An error will occur if the inputs given to the procedure do not match its signature. A function signature reveals a great deal about the subroutine type. It allows the user to create subroutines with the same name but distinct signatures, i.e. different arguments. Different subroutines may have the same name in Perl, but their arguments must be distinct. Example: sub examplefunc($variable) { statement; } sub examplefunc($variable1, $variable2) { statement; }

In the above code, the names of the subroutines are identical, but their parameter counts are distinct; as a result, they are not deemed to be distinct subroutines, and our Perl code will not raise an error. Passing Parameters of a Type other than that Specified in the Signature When a subroutine is defined with a signature, it must take arguments of the same type as its signature. If an argument different than the function signature is given, an error will be generated, causing the code compilation to fail. Example: #!/usr/bin/perl # Defining the Function Signature sub example(Int $variable) { return $variable / 2; } # Function-Call print example(66);

216   ◾    Mastering Perl

If we pass an argument of a type other than the function signature, the following error will be generated: #!/usr/bin/perl # Defining the Function Signature sub example(Int $variable) { return $variable / 2; } # Function Call with the # string type parameter print example("66");

Difference in Number of Arguments When a function signature is defined, it also includes the number and type of arguments that can be passed to it. If we call the function with a different number of arguments, Perl will throw an error because functions with different signatures have different meanings. Example: #!/usr/bin/perl # Defining Function-Signature sub example(Int $variable) { return $variable / 2; } # Function Call with the # two arguments print example(66, 49);

Function signature is a useful feature, but it can be very annoying for some programmers because it restricts the use of the function to a specific type of parameter. There are no restrictions on the type of parameters that can pass to the function if it is defined without a signature.

Subroutines in Perl   ◾    217

Example: #!/usr/bin/perl # Defining Function-Signature sub example($variable) { return $variable / 2; } # Function Call with the Integer argument # written as string type print example("66");

The above code declares a function with no specific argument type, so when an integer value is passed to it as a string, it automatically converts the argument to integer form and returns the result. However, if we call the function with a string argument and the operation to be performed on it requires an integer value, we will get the following error: #!/usr/bin/perl # Defining Function-Signature sub example($variable) { return $variable / 2; } # Function Call with the # string type argument print example("Peeks");

PASSING COMPLEX PARAMETERS TO A SUBROUTINE A Perl function or subroutine is a collection of statements that perform a specific task. The user wants to reuse code in every programming language. So the user places the code section in a function or subroutine to avoid having to rewrite the same code repeatedly. As a result, function or subroutine is used in all programming languages. These functions or subroutines can accept various data structures as parameters. Some of these are discussed further below: • Passing lists or arrays to a subroutine • Passing references to a subroutine

218   ◾    Mastering Perl

• Passing file handles to a subroutine • Passing hashes to a subroutine Passing arrays or lists to a subroutine: An array or list can be passed as a parameter to the subroutine, and an array variable @_ is used to accept the list value inside the subroutine or function. First example: A single list is passed to the subroutine, and its elements are displayed. #!/usr/bin/perl # Defining-Subroutine sub Display_List { # array variable to store the # passed arguments my @List1 = @_; # Printing passed list elements print "Given list is @List1\n"; } # Driver-Code # passing-list @list = (1, 2, 3, 4); # Calling the Subroutine with # list-parameter Display_List(@list);

Second example: In this case, two lists are passed to the subroutine, and their contents are displayed. #!/usr/bin/perl # Defining-Subroutine sub Display_List

Subroutines in Perl   ◾    219 { # array variable to store # the passed arguments my @List3 = @_; # Printing the passed lists' elements print "The Given lists' elements are @List3\n"; } # Driver-Code # passing lists @List1 = (11, 12, 13, 14); @List2 = (20, 30, 40, 50); # Calling Subroutine with # the list parameters Display_List(@List1, @List2);

Third example: A scalar argument and a list are passed to the subroutine, and the list elements are displayed. #!/usr/bin/perl # Defining-Subroutine sub Display_List { # array variable to store # passed arguments my @List2 = @_; # Printing passed list and scalar elements print "The List and scalar elements are @List2\n"; } # Driver-Code # passing lists @List = (11, 12, 13, 14);

220   ◾    Mastering Perl # passing the scalar argument $scalar = 100; # Calling Subroutine with # the list parameters Display_List(@List, $scalar);

Passing references to subroutines: References can also be passed as parameters to subroutines. The array reference is passed to the subroutine, and the maximum value of the array elements is returned. Example: #!/usr/bin/perl use warnings; use strict; # Creating an array of the some elements my @Array = (20, 30, 40, 50, 60); # Making reference to the above array # and calling the subroutine with # reference of the array as the parameter my $m = max(\@Array); # Defining-subroutine sub max { # Getting array elements my $Array_ref = $_[0]; my $k = $Array_ref->[0]; # Iterating over each element of # the array and finding maximum value for(@$Array_ref) { $k = $_ if($k < $_); } print "Max of @Array is $k\n"; }

Subroutines in Perl   ◾    221

Passing a hash to a subroutine: A hash can also be passed as a parameter to a subroutine, which displays its key-value pair. Example: #!/usr/bin/perl # Subroutine-definition sub Display_Hash { # Hash variable to store the # passed arguments my (%Hash_var) = @_; # Displaying passed list elements foreach my $key (keys %Hash_var) { my $value = $Hash_var{$key}; print "$key : $value\n"; } } # Driver-Code # defining hash %Hash = ('Company' => 'PeeksforPeeks', 'Location' => 'Delhi'); # calling Subroutine with the hash parameter Display_Hash(%Hash);

Passing file handles to a subroutine: To create a file or access its contents, a FileHandle is required. A FileHandle is nothing more than a structure used with the operators to access the file in a specific mode, such as reading, writing, appending, and so on. FileHandles can also be passed as a parameter to a subroutine to perform various operations on Files. A FileHandle is passed to a subroutine in the following example: Example: #!/usr/bin/perl sub printem

222   ◾    Mastering Perl { my $file = shift; while () { print; } } open(fh, "Hello1.txt") or die "File '$filename' cannot be opened"; printem *fh;

MUTABLE AND IMMUTABLE PARAMETERS A Perl function or subroutine is a collection of statements that perform a specific task. The user wants to reuse code in every programming language. So the user places the code section in a function or subroutine to avoid having to write the code repeatedly. These subroutines have parameters that define the type and number of arguments that can be passed to the function when it is called. These arguments are used to evaluate the values passed to the function using the function’s expressions. These values are then passed to the calling function and returned to the specified parameters. Example: sub Function1(parameter-1, parameter-2) { statement; }

Mutable Parameters These are parameters, the values of which are changed inside the function to which they have been passed. It indicates that when a parameter is supplied to a function through the caller function, its value is tied to the parameter in the called function, thus any changes made to the value in the called function will also be reflected in the parameter passed by the caller function. Immutable Parameters These arguments are of those kinds, the values of which cannot be altered inside the function to which they are supplied. It indicates that the

Subroutines in Perl   ◾    223

subroutine gets a value rather than a variable when a parameter is supplied to the function through the caller function. Consequently, any modifications to the function parameter are not reflected. Perl’s subroutine parameters are immutable by default, meaning they cannot modify inside a function, and one cannot inadvertently alter the arguments of the calling function. In specific programming languages, this is referred to as “call by value,” which indicates that the subroutine being called gets a value rather than the variable, so the parameters of the calling function are not altered. Example: #!/usr/bin/perl # Function-Definition sub Func(Int $variable) { # Operation to perform $variable /= 2; } # Defining local variable my $value = 40; # Function Call with the local variable print Func($value);

Traits are used to change the properties of these parameters. The value of a parameter can be changed within a subroutine using traits. Traits These are predefined built-in subroutines that alter the method’s behavior when run at compile time when used within a method. Traits can even be used to modify the method’s body or tag the method with metadata. Depending on their usage, traits can be of various types, such as: • is cached trait automatically caches the function’s return value based on the arguments passed to it. • is rw trait enables writable accessors to subroutine parameters.

224   ◾    Mastering Perl

• is copy trait allows us to change the value of a parameter within a subroutine but not the argument in the caller function. Example: Use of the is copy trait #!/usr/bin/perl # Function Definition using the # 'is copy' trait sub Func(Int $variable is copy) { # Operation to be performed $variable += 5; } # Defining the local variable my $value = 20; # Function Call with the local variable print Func($value), "\n"; # Checking if # the $value gets updated or not print $value;

Because Perl does not allow the modification of arguments within a subroutine by default, the copy trait is used in the above code. This trait enables the program to assign the caller function’s parameter value to the subroutine being called a parameter. This trait, however, will only affect the value of the argument in the called function. Example: Use of the is rw trait #!/usr/bin/perl # Function Definition using the # 'is rw' trait sub Func(Int $variable is rw) { # Operation to perform $variable += 5; }

Subroutines in Perl   ◾    225 # Defining local variable my $value = 20; # Function Call with the local variable print Func($value), "\n"; # Checking if # the $value gets updated or not print $value;

When is rw is used instead of is copy trait in the preceding code, the value of argument passed in the caller function is also updated. When the is rw trait is used, the argument of the called function is bound with the argument of the caller function, so if the former value changes, the latter is immediately updated. This is because a process known as “call by reference.” Because both arguments refer to the same memory location (because of the is rw trait); as a result, the parameters are fully mutable.

MULTIPLE SUBROUTINES A Perl function or subroutine is a collection of statements that perform a specific task. Every programming language user wishes to reuse code. So the user places the code section in a function or subroutine to avoid having to write the code repeatedly. Although the terms function, subroutine, and method are interchangeable in Perl, they are not in other programming languages. Because it is created with the keyword sub, the terms subroutines are commonly used in Perl programming. When a function is called, Perl stops executing its entire program and jumps to the function to execute it before returning to the section of code that was previously running. The return statement can be avoided. Subroutine Definition In Perl, the general form of defining a subroutine is as follows: sub subroutine_name { # body of the method or subroutine }

Because Perl allows you to write multiple subroutines with the same name unless they have different signatures, a program in Perl can contain

226   ◾    Mastering Perl

multiple subroutines with the same name without generating an error. This can be defined by varying the arity of each subroutine with the same name. Subroutine arity: Perl subroutines can have the same name as long as they have a different set of arity. The number of arguments a subroutine has is referred to as its arity. These arguments could be of a different data type or not. The Perl program will not generate an error as long as the number of subroutines differs. Use of the “multi” Keyword The keyword “multi” can use to create multiple subroutines in Perl. This is useful for creating multiple subroutines with the same name. Example: multi Func1($var){statement}; multi Func1($var1, $var2){statement-1; statement-2;}

Multiple subroutines are commonly used to create built-in functions and most operators in a programming language such as Perl. The program’s complexity is reduced by not using different names for each other subroutine. Whatever code statement is required, simply pass the number of arguments for that function, and the work will be completed. In this case, compiler will select the version of the subroutine, the function signature of which matches the one invoked. Various programs, such as factorial of a number, Fibonacci series, and so on, require the use of more than one function to solve the problem. The use of multiple subroutines will aid in the reduction of the complexity of such programs. First example: Fibonacci series sum #!/usr/bin/perl # Program to print sum of the fibonacci series   # Function for the $n = 0 multi Fibonacci_func(0) { 1; # returning 1 }

Subroutines in Perl   ◾    227 # Function for the $n = 1 multi Fibonacci_func(1) { 1; # returning 1 } # Recursive function to calculate the Sum multi Fibonacci_func(Int $n where $n > 1) { Fibonacci_func($n - 2) + Fibonacci_func($n - 1); } # Printing sum # using the Function Call print Fibonacci_func(27);

To calculate the sum of Fibonacci series, the preceding example employs multiple subroutines. Second example: A number factorial #!/usr/bin/perl # Program to print factorial of number # Factorial of 0 multi Factorial(0) { 1; # returning 1 } # Recursive Function # to calculate the Factorial multi Factorial(Int $n where $n > 0) { $n * Factorial($n - 1); # Recursive-Call } # Printing result # using the Function Call print Factorial(25);

In the preceding examples, the program declares multiple subroutines with the same name but different arity using the “multi” keyword.

228   ◾    Mastering Perl

return() FUNCTION In Perl, the return() function returns value at the end of a subroutine, block, or do function. The returned value could be a scalar, an array, or a hash depending on the context. Syntax: return Value Returns: a List in the Scalar Context

If no argument is passed to the return function, it returns an empty list in the list context, undef in the scalar context, and nothing in the void context. First example: #!/usr/bin/perl -w # Subroutine for the Multiplication sub Mul($$) { my($x, $y ) = @_; my $z = $x * $y; # Return-Value return($x, $y, $z); } # Calling in Scalar context $retval = Mul(35, 20); print ("The Return value is $retval\n" ); # Calling in the list context @retval = Mul(35, 20); print ("The Return value is @retval\n" );

Second example: #!/usr/bin/perl -w # Subroutine for the Subtraction sub Sub($$)

Subroutines in Perl   ◾    229 { my($x, $y ) = @_; my $z = $x - $y; # Return Value return($x, $y, $z); } # Calling in the Scalar context $retval = Sub(35, 20); print ("The Return value is $retval\n" ); # Calling in the list context @retval = Sub(35, 20); print ("The Return value is @retval\n" );

REFERENCES IN PERL Variables are used in Perl to access data stored in memory (all data and functions are stored in memory). Variables are given data values that are then used in various operations. Perl reference allows you to access the same data but through a different variable. In Perl, a reference is a scalar data type that holds the location of another variable. Other variables include scalars, hashes, arrays, function names, and so on. Nested data structures are simple to construct because a user can create a list that contains references to another list that contains references to arrays, scalar, hashes, and so on. Making a Reference We can make references to scalar value, hash, array, function, and so on. To make a reference, define a new scalar variable and prefix the variable’s name (the reference of which we want to make) with a backslash. Making references to different data types: # Array-Reference # defining-array @array = ('1', '2', '3'); # making reference of the array variable $reference_array = \@array;

230   ◾    Mastering Perl # Hash-Reference # defining-hash %hash = ('1'=>'a', '2'=>'b', '3'=>'c'); # make reference of hash variable $reference_hash = \%hash; # Scalar Value Reference # defining-scalar $scalar_val = 2431; # making reference of the scalar variable $reference_scalar = \$scalar_val;

Notes: • The curly brackets {} around key and value pairs can be used to create a reference to an anonymous hash. Example: # creating reference to the anonymous hash $ref_to_anonymous_hash = {'PFP' => '1', 'Peeks' => '2'};

• The square brackets [] can use to create a reference to an anonymous array. Example: # creating reference to anonymous array $ref_to_anonymous_array = [30, 40, ['P', 'F', 'P']];

• Sub can also be used to create a reference to an anonymous subroutine. There will be no name for the sub here. Example: # creating reference to anonymous subroutine $ref_to_anonymous_subroutine = sub { print "PeeksforPeeks\n"};

• It is not possible to create reference to an input/output handle, such as dirhandle or FileHandle.

Subroutines in Perl   ◾    231

Dereferencing Now that we’ve made the reference, we must use it to get to the value. Dereferencing is a method of gaining access to the value in the memory pointed to by the reference. Depending on the type of variable, we use prefix $, @, percent, or & to dereference (reference can point to a array, scalar, hash, etc.). First example: # Program to illustrate # Dereferencing of an Array # defining an array @array = ('1', '2', '3'); # making reference to an array variable $reference_array = \@array; # Dereferencing # printing value stored # at $reference_array by prefixing # @ as it is array reference print @$reference_array;

Second example: # program to illustrate # the Dereferencing of a Hash # defining hash %hash = ('1'=>'a', '2'=>'b', '3'=>'c'); # creating reference to hash variable $reference_hash = \%hash; # Dereferencing # printing value stored # at $reference_hash by prefixing # % as it is a hash reference print %$reference_hash;

232   ◾    Mastering Perl

Third example: # program to illustrate # Dereferencing of Scalar # defining scalar $scalar = 2431; # creating reference to scalar variable $reference_scalar = \$scalar; # Dereferencing # printing value stored # at $reference_scalar by prefixing # $ as it is Scalar reference print $$reference_scalar;

PASS BY REFERENCE When variable is passed by reference, the function operates on the function’s original data. The function can change the original value of a variable by passing it by reference. When the values of the elements in the argument arrays @_ are changed, so do the values of the corresponding arguments. This is what parameter passing by reference accomplishes. In the following example, updating the elements of an array @a in subroutine sample changes the value of the parameters, which is reflected throughout the program. As a result, when parameters are referenced, changing their value in the function changes their value in the main program. First example: #!/usr/bin/perl # Initialising array 'a' @a = (0..10); # Array before the subroutine call print("The Values of an array before function call: = @a\n"); # calling subroutine 'sample' sample(@a);

Subroutines in Perl   ◾    233 # Array after the subroutine call print("The Values of an array after function call: = @a"); # Subroutine to represent # Passing by Reference sub sample { $_[0] = "A"; $_[1] = "B"; }

The program operates as follows: • An array with the values ranging from 0 to 10 is defined. • This array is then passed to the “sample” subroutine. • A subroutine called “sample” has already been defined. The first and second parameters’ values are changed within this via the argument array @_. • After calling the subroutine, the values of the array @a are displayed. The first two scalar values are now updated to A and B, respectively. Second example: #!/usr/bin/perl # Initializing values to scalar # variables x and y my $x = 10; my $y = 20; # Values before the subroutine call print "Before calling the subroutine x = $x, y = $y \n"; # Subroutine call sample($x, $y); # Values after the subroutine call print "After calling the subroutine x = $x, y = $y ";

234   ◾    Mastering Perl # Subroutine sample sub sample { $_[0] = 1; $_[1] = 2; }

PERL RECURSION Recursion is a mechanism that allows a function to call itself repeatedly until the required condition is met. When the function call statement is written within the same function, the function is said to be recursive. The argument passed to a function is retrieved from default array @_, with each value accessible via $_[0], $_[1], and so on. First example: The following example computes the factorial of a number. The Factorial of any number n is (n)*(n-1)*(n-2)*....*1. e.g.: 4! = 4*3*2*1 = 24 3! = 3*2*1 = 6 2! = 2*1 = 2 1! = 1 0! = 0 #!/usr/bin/perl # Program to calculate Factorial sub fact { # Retrieving first argument # passed with the function-calling my $x = $_[0]; # checking if value is 0 or 1 if ($x == 0 || $x == 1) { return 1; } # Recursively calling function with next value # which is one less than current one

Subroutines in Perl   ◾    235 else { return $x * fact($x - 1); } } # Driver-Code $a = 5; # Function call and printing the result after return print "The Factorial of a number $a is ", fact($a);

The program works as follows: • Step 1: When the value of scalar a is 0 or 1, the function returns 1 because both 0! and 1! are 1. • Step 2: If the value of the scalar a is 2, then fac(x-1) calls fac(1), which returns 1. As a result, 2*factorial(1) = 2*1 = 2. As a result, it will return 2. • Step 3: Similarly, when higher values are passed to the function, the argument value decreases by 1 with each call and computes until the value reaches 1. Second example: The following example computes the Fibonacci series up to a given number. #!/usr/bin/perl # Program to print Fibonacci series sub fib { # Retrieving values from parameter my $c = shift; my $d = shift; # Number till which the series is to print my $n = shift; # Check for end value if ($d > $n)

236   ◾    Mastering Perl { return 1; } # Printing number print " $d"; # Recursive Function Call fib($d, $c + $d, $n); } # Driver Code # Number till which series is to print $m = 5; # First two elements of series $x = 0; $y = 1; print "$x"; # Function call with the required parameters fib($x, $y, $m);

Here’s how the program works: • Step 1: The function fib() is called with 3 parameters, the first two of which are 0 and 1, while $n is number till which series is to be printed. • Step 2: These values are transferred in the form of an array, the contents of which are retrieved using shift. • Step 3: For each call, the first two values are retrieved using shift and stored in scalars c and d. These two values are now added to yield the next value in the series. This step is repeated until the value reaches the end value specified by the user. In this chapter, we covered subroutines in Perl where we discussed function signature, passing complex parameters to a subroutine, and mutable and immutable parameters. Moreover, we discuss multiple subroutines use of return() function, pass by reference, and recursion.

Appraisal Perl is a widely used cross-platform, open-source programming language in both the commercial and private computing industries. Perl was favored by Web developers in the late 20th and early 21st centuries because of its adaptable text-processing and problem-solving skills. Larry Wall, an American programmer and linguist, published Perl 1.0 for Unix-based computers for the first time in December 1987. This early version of Perl was an intuitive, easily coded language for reading, extracting, and printing information from text files; it was also capable of doing other systems management tasks. Perl, which is frequently believed to stand for “practical extraction and report language,” was inspired by existing programming languages, such as C, BASIC, and AWK, but its wide usage of common English terminology reflected Wall’s linguistic background. Perl was a milestone product in promoting the open-source model, a collaborative approach to software development as opposed to a proprietary one. Perl is a programming language designed for script manipulation. However, Perl is now used for a wide range of purposes, including web development, graphical user interface (GUI) development, system administration, and many others. It is a reliable and cross-platform programming language. Perl CGI is used for web development. CGI is the system gateway that communicates with the web browser and Perl. Its most common application is extracting information from a text file and printing a report to convert a text file into another format. This is due to its name being derived from the phrase “Practical Extraction and Report Language.” Perl scripts are programs written in Perl, whereas Perl programs are system programs that execute Perl scripts. Perl is a scripting language. When we run a Perl program, it is first compiled into byte code and then converted into machine instructions. Writing something in Perl rather than C saves time. DOI: 10.1201/9781003358442-9

237

238   ◾    Appraisal

It works with the vast majority of operating systems and is included in the Oxford English Dictionary. It borrows concepts and syntax from a variety of languages, including AWK, bourne shell, C, sed, and even English.

HISTORY OF PERL Larry Wall created Perl in 1987 as a scripting language to help with report processing. On December 18, 1987, it was released in version 1.0. Perl 2 was released in 1988, and it included a much improved regular expression engine. Perl 3 was released in 1989, and it included support for binary data streams. Perl 4, released in 1991, had better documentation than previous versions. On October 17, 1994, Perl 5 was released. Its most recent version included many new features, such as objects, variables, references, and modules. The most recent version, 5.24, was released on May 9, 2016.

FEATURES OF PERL It has a straightforward object-oriented programming syntax. It can easily expand because it supports 25,000 open-source modules. Unicode is supported. It includes powerful tools for processing text to make it compatible with mark-up languages, such as HTML and XML. It supports third-party databases, such as Oracle and MySQL. It can embed in other systems like web servers and database servers. It is GNU-licensed open-source software. Perl is used to write many frameworks. It is capable of processing encrypted web data, including e-commerce transactions. It is a platform-independent language. It includes a regular expression engine that can transform any type of text.

LICENSING FOR PERL Larry Wall owns the copyright (C) to Perl 5. It is free and open-source software. It may be redistributed or modified under the terms of the GNU and Artistic Licenses.

Appraisal   ◾    239

The GNU General Public License offers its users free and open-source software. Any program derived from GNU-licensed source code must use the same license. According to the Artistic license, a package derived from Perl must clearly highlight its modifications. The original module, as well as the derived one, should be distributed. Above all, the original author must be acknowledged as the package’s owner. Users should able to distinguish between original and derived modules.

PERL AND THE WEB Because of its text manipulation capabilities and quick development cycle, Perl was once the most popular web programming language. Perl is commonly referred to as “the duct tape of the Internet.” Perl is capable of processing encrypted Web data, including e-commerce transactions. Perl can be embedded in web servers to speed up processing by up to 2000%. The Perl module mod Perl enables the Apache web server to include a Perl interpreter. Perl’s DBI package simplifies web-database integration.

PERL IS INTERPRETED Because Perl is an interpreted language, our code can run without being compiled into a non-portable executable program. Traditional compilers translate programs into machine code. When you run a Perl program, it is first compiled into byte code, which is then converted into machine instructions (as the program runs). As a result, it differs from shells or Tcl, which are strictly interpreted without an intermediate representation. It’s also unlike most C or C++ versions, which are compiled directly into machine-dependent formats. It is in the middle, alongside Python, AWK, and Emacs. elc files.

ADVANTAGES Perl has the following advantages: • Options: Perl users have numerous options for writing programs or solving problems.

240   ◾    Appraisal

• Flexible: The language’s design and syntax allow users to code in their preferred programming style. • Open source: It’s free to use. Anyone can access, develop, and use Perl on various platforms for free. • Availability: It comes pre-installed in many places, and the Comprehensive Perl Archive Network contains over 25,000 Perl modules. The majority of operating systems also support it.

DISADVANTAGES The main disadvantage of Perl is that it is a relatively messy language in a variety of ways: • Hard to read: It’s difficult to read. According to some developers, Perl is more difficult to read and less streamlined than newer languages such as Python. Because of the numerous ways to write a Perl program, the code can become disorganized and untidy. • Difficult to debug: Debugging and fixing problems can be difficult because Perl code can be obscure or messy. • Flaws in performance: The same flexibility that makes Perl useful can also make it slow. This is because flexibility can lead to inefficiencies and redundancy, making compilation time longer.

PERL VS PYTHON Perl and Python have a common ancestor. Both were created to make scripting easier. Perl was created to give Unix scripts a C-like structure. Python was created to make C easier to use and ready for scripting. Syntactically, Perl and Python are very similar, and translating from Perl to Python is relatively simple with only a few significant syntax changes. However, there are four significant differences: • A semicolon terminates lines in Perl. • Python lacks curly braces and indentation, whereas Perl does. • Variable names in Perl are styled with variables, such as $x, % x, and x. In Python, variable names are styled without a variable indicator, such as x. • In Python, the print statement inserts a new line at the end of the output.

Appraisal   ◾    241

Other differences include: • Perl can be messy, whereas Python is more streamlined. • In Perl, numerous ways exist to accomplish a task, whereas Python is designed to provide a single clear path to any given function. • Python is more readable than Perl. • Python is commonly considered one of the best programming languages to learn and one of the most user-friendly for new developers. • Python is a newer programming language than Perl. • Perl is integrated into the source code of a web application. • Python is a powerful programming language because of its reputation as a dynamic programming language with various applications ranging from web development to machine learning. • Python has more support in the open-source developer community. Perl

Python

It is a high-level, interpreter-based, dynamic programming language. Perl can download for Unix/Linux, macOS, or Windows from https://www. perl.org/get.html.

It is a high-level, general-purpose language of programming with an interpreter. Python can download for Unix/Linux, macOS, Windows, and other operating systems from https://www.python.org/ downloads/. Python aimed to make writing simple and logical code for small and large projects and applications more accessible.

Perl’s goal was to simplify the report creation process, which later underwent many changes and revisions to include many new features and capabilities. When compared to Python code, Perl code is not as simple. Perl has outstanding library support and can handle operations at the OS level using built-in functions. The OOP support available is limited. Braces are used to mark and identify code blocks. Whitespaces are not crucial in Perl.

Python code is more straightforward and more understandable. To handle such operations, Python requires the assistance of third-party libraries. Python provides excellent support for object-oriented programming. Indentation is used to mark and identify code blocks. Whitespaces are significant in Python and can cause syntax errors. (Continued)

242   ◾    Appraisal Perl

Python

It facilitates text processing because Perl includes support for Regular expressions. To end a code line in Perl, use a semicolon(;). The file extension for Perl is .pl.

To handle Regular expressions, Python requires the use of external functions. At the end of each code line, semicolons (;) are not required. Python files have the extension. py.

PERL VS JAVA Larry Wall invented Perl in 1987. Perl supports both object-oriented and procedural programming. It is similar to C and C++. Perl was initially designed to process text. Java is a well-known programming language. Java is both a programming language and a computer platform. Sun Microsystems published Java in 1995, on the initiative of James Gosling. Oracle claims that java is used on 3 billion devices worldwide. It is designed to allow developers to WRITE ONCE, RUN ANYWHERE, which means that a Java application may be produced on one platform and executed on any other platform that supports the JVM. The following are some critical distinctions between Perl and Java:

Feature

Introduction

Perl

“Perl is a general-purpose, high-level programming language popular for CGI scripts.” CPanel and Bugzilla are two popular Perl projects. Initially, it was intended to replace sophisticated shell scripts. Compiled format Perl 6 is compiled to Parrot Bytecode, whereas Perl 5 and earlier versions are interpreted languages. It is saved with the extension. pbc. Associative arrays Perl defines associative arrays extremely succinctly.

Java

Java is both a programming language and a platform for computing. There are still programs and websites that will not operate unless you have Java installed. It is quick, safe, and dependable. Java applications are translated into bytecode.

Java bytecode may be sent across the network and then run on any system that has a JVM. It is saved with the extension.class. (Continued)

Appraisal   ◾    243 Feature

Perl

Focus

Perl excels at supporting common activities like file scanning and report creation.

File extension Typed method Comments and documentation

End of statement

Java

There is no concise method to create associative arrays in Java. It does, however, hash implementations. Programs in Perl are saved with Programs in Java are saved with. .pl extension. java extension. Eg: MyFile1.pl Eg: MyFile1.java Perl is dynamically typed, which Java is statically typed, which means means that most type checking that most of its type checking occurs during execution. occurs at build time. Inline comments in the Perl are Single-line comments in the Java written using # are declared using // E.g. #Inline-Comment in the Eg: //Single-line Comment. Perl The Multiline comments are written Documentation in Perl is done using /*……*/ using = and =cut. Eg: /* it is a multiline comment */ Eg: =Perl documentation follows Documentation in Java is done following syntax =cut using. /**…………*/ Eg: /**Documentation in the Java*/ Every statement in Perl must Every statement in Java must finish with a semi-colon (;) conclude with a semi-colon (;)

PERL VS C/C++ Perl is a dynamic, high-level, interpreted, general-purpose programming language. It was created in 1987 by Larry Wall. There is no official acronym for Perl, although “Practical Extraction and Reporting Language” is the most common. Some programmers refer to Perl as “Pathologically Eclectic Rubbish Lister” and “Practically Everything Really Likable.” The abbreviation “Practical Extraction and Reporting Language” is often used since Perl was initially designed for text processing, such as extracting the necessary information from a specific text file and converting the text file to a new format. Both procedural and object-oriented programming is supported. C++ is a general-purpose programming language commonly utilized for competitive programming these days. It supports imperative, object-oriented, and generic programming. C++ operates on various platforms, including Windows, Linux, Unix, and Mac.

244   ◾    Appraisal

Below are a few significant differences between Perl and C/C++: Feature

Perl

C/C++

Driver function(main())

Perl does not require an explicit driver function.

Compilation process

Perl is a programming language that is interpreted. Closures containing inaccessible private data can be used as objects in Perl. The .pl extension is used to store Perl scripts. For instance, perlDocument .pl

C/C++ code must execute the main() function in order to compile. C++ is a language for generalpurpose object-oriented programming (OOP). C/C++ does not allow closures, which may be considered of functions that can be stored as variables. The file extensions. c and.cpp are used to save C and C++ codes, respectively. MyFile.c and myFile.cpp are two examples. Braces are not required after if and loops in C/C++. Ex: if ( condition ) statement;

Closures

File extension

Braces

String declaration

Comments

Braces must be used around the “then” part of an if statement in Perl. Ex: if ( condition ) { statement } Strings are declared in Perl using single quotes. Double quotes force an evaluation of the string’s contents. Example: $x = “peeksforpeeks” In Perl, we utilize # for inline comments. e.g. #Inline-Comment in the Perl

To define a string in C/C++, use double quotes. Example: string s =“peeksforpeeks”

C/C++ uses // for the Inline comments. e.g. //Inline-Comment in the C/C++.

Perl program for adding two numbers: #!/usr/bin/perl # Perl program for adding two numbers $choice = 13; $choice2 = 15; $res = add($choice, $choice2); print "Result is $res";

Appraisal   ◾    245 # Subroutine to perform # the addition operation sub add { ($c, $d) = @_; $res = $c + $d; return $res; }

Is It Worth Learning? Perl Excels at text manipulation. It’s a fantastic language for processing logs, data munging, and pretty much anything else we can do from the command line. Despite its history as the driving force behind the monstrosity that is Perl CGI, there are new frameworks for modern web apps such as Dancer. Perl is still a viable option for the modern programming. CPAN is still operational, and most useful modules are still maintained. Books like Modern Perl demonstrate how to keep Perl modern while avoiding past pitfalls. Keeping Perl Relevant Perl grew from a “Swiss Army Chainsaw” language to a robust scripting language for broad purposes. It has developed to the extent where it excels at certain challenges, but others should be avoided unless we enjoy the language. We won’t use it in a GUI, but we won’t ignore it while dealing with data or a command line unless there’s a compelling reason to do so. The language continues to be revised, and the current baseline standard is 5.8. MacOS deploys with Perl, it works on the Linux subsystem for Windows or through Strawberry Perl for scripting (though it’s probably not anyone’s first choice), and it’s present on practically every Linux distribution (and needed by many) and every MacOS installation. It is accessible and standard on any current POSIX platform, and it can even function properly on Windows. We used it as the foundation for a scripting language to solve the lack of a MacOS RMM tool. On an earlier Mac, there was no installation required, and it took less than a day to implement. Almost every Mac that is onboarded uses this scripting engine, which has not been updated in any significant manner since its first deployment.

246   ◾    Appraisal

What Does Perl Serve? Perl is used for database management, system administration, and the development of GUIs. Perl was previously referred to as the “duct tape of the internet” due to its extensive functionality. It is one of the “P” choices in the web development LAMP technology stack (the other options are Python and PHP). The remaining letters represent Linux, Apache, and MySQL. Here are the primary uses of Perl today: • The management of systems: Perl may be used to automate or execute system management duties. These responsibilities include renaming several files in a directory or modifying a specific text component in each source file in a directory tree. • Web development: Perl may be used to develop web apps. We may utilize frameworks such as Dancer in the Perl web development process. Web pages may also be served using Perl. • Networking programming: We can utilize Perl’s built-in functions to create client/server applications. Perl also contains modules that make writing typical networking tasks, such as pinging distant computers, easier. • Data management on the cloud: Many businesses have relocated their data to a public cloud nowadays. Perl can assist in cloud data management and virtual machine administration. Perl Learning If we want to work in technology, we should learn Perl. Companies that use Perl to build their system administration processes, network programs, and websites require Perl developers. Amazon, Roblox, Venmo, and MIT are among these companies. Perl experts hold titles like Solutions Engineer, Software Engineer, Web Developer, and Database Engineer. Perl is a great way to round out our understanding of current technologies if we want to work as a coder or system administrator in the tech industry. Why Should We Study Perl? Some of the reasons why we should learn Perl are as follows: Perl is an excellent general-purpose programming language. Perl is used in a wide range of applications. These include database management, web development, system administration, and network programming.

Appraisal   ◾    247

Perl is used in intriguing ways. Bioinformatics programmers construct software for comprehending biological data sets. The expanding subject of genomics utilizes bioinformatics industry expertise. We may acquire genomic sequences and investigate population genetics using Perl. Perl is based on linguistic concepts, and it remains an excellent textmanipulation language today. Regex, HTML parsing, and JSON manipulation come to mind. Perl can also be used to implement language processing features such as voice recognition and text-to-speech translation. Using the widespread Test Anything Protocol, you can also test applications automatically using Perl (TAP). In conclusion, knowing Perl will provide us with intriguing options in our web development profession. Perl coders are in-demand. Once we have mastered Perl, we may utilize it to fuel our own projects or find employment. According to the TIOBE Index, a website that evaluates the popularity of programming languages based on search engine results, Perl is now ranked 17th out of 50 programming languages. The index incorporates the results of 25 search engines. It counts a number of hits for a particular programming language, and the number of hits is used to establish that language’s ranking in the index. This, combined with other data such as the frequency of job posts that mention Perl, shows that while Perl is not most popular programming language at the moment, it is still in use and hence a desirable talent to acquire. There are over 15,000 job postings on LinkedIn and over 10,000 on Glassdoor that include Perl. Even while Perl may not be the most popular programming language today, firms continue to use it to run their web businesses, and they continue to seek individuals with this skill set. How Long Does It Take to Learn Perl? Give yourself three months to learn the fundamentals and begin writing programs. This assumes that we spend an hour a day learning this language. This estimate is based on the fact that it takes about eight weeks to learn the fundamentals of Python, another scripting language that debuted around the same time as Perl (1991) and is used for many similar tasks. However, one significant difference is that, whereas Python was designed to have a limited number of ways to perform a task, Perl was designed with the philosophy of “There’s more than one way to do it.” This means we may need to devote more time to learning the fundamentals of Perl.

248   ◾    Appraisal

Is Perl Difficult to Learn? Perl can be challenging for beginners. Having prior experience with other scripting languages, on the other hand, shortens the learning curve. Learning Perl will be simple if we have some Python experience. We must install software and interact with the command line to get started with Perl. If we’ve never done it before, do it before learning the Perl syntax. Perl Learn has straightforward installation instructions for all platforms. Breakpoints of a Debugger in Perl Controlling program execution in Perl is accomplished by instructing the debugger to execute up to a specific point in the program known as a breakpoint. These breakpoints allow the user to segment the program and search for errors. The following debugger commands are used to create such breakpoints, as well as commands that are executed until a breakpoint is reached. b-Command The b-command is used to set a breakpoint in a program. This command instructs the debugger to stop the program whenever a specific line is executed. For instance, the following command instructs the debugger to halt when it is about to execute line 12: DB b 12

(If the line is unbreakable, the debugger will return that Line 12 is not breakable.) A program can have an unlimited number of breakpoints. When the debugger is about to execute a statement that contains a breakpoint, the program will halt. b-command also accepts subroutine names: DB b valuedir

This sets a breakpoint at the subroutine valuedir very first executable statement. The b-command can also stop a program only when a certain condition is met.

Appraisal   ◾    249

The following command, for instance, instructs the debugger to halt when it is about to execute line 12 and variable $vardir is equal to null: DB b 12 ($vardir eq "")

The b statement can be used to specify any legal Perl conditional expression. A breakpoint can be set at any of the lines in a multiline statement. As an example: 16: print ("Peeks", 17: " for Peeks here");

Line 16 can be used as a breakpoint, but not line 17. c-Command The c-command instructs the debugger to continue debugging until it reaches a breakpoint or the end of the program. DB c main::(debugtest:12):

$vardir =~ d/^\d+|\d+$//h;

DB

When the debugger is about to reach line 12, where our breakpoint is set, the program is halted and the line is displayed, as the debugger always displays the line that is about to be executed. The debugger generates a prompt for another debugging command here. This prompt allows us to continue the execution process one statement at a time by typing n or s, to continue the execution process by typing c, to set more breakpoints by typing b, or to perform any other debugging operation. A temporary (one-time-only) breakpoint can be set using the c-command and a line number: DB c 12 main::(debugtest:12):

&readsubdirs($vardir);

250   ◾    Appraisal

The c-command argument 12 instructs the debugger to set a temporary breakpoint at line 12 and then continue execution. When the debugger reaches line 12, it stops the execution process, displays the line, and removes the breakpoint. The c-command is used to define a temporary breakpoint when a person wants to skip a few lines of code without wasting execution time by going through the program one statement at a time. Using c also eliminates the need to use b to define a breakpoint and then delete it with the d-command. L Command and Breakpoints DB L 4:

$count = 0;

5:

$vardir = "";

6:

while (1) {

8:

if ($vardir eq "") {

11:

$vardir =~ d/^\d+|\d+$//h;

break if (1)

Lines 4–8 have been executed, and a breakpoint has been set for line 11. (Line 7 isn’t included because it’s a comment.) Breakpoints can distinguish from executed lines by examining the conditional expressions immediately following the breakpoint. The conditional expression, in this case, is set to (1), indicating that the breakpoint is always effective. d and D Commands When a breakpoint’s job is complete, it can delete with the d-command. DB d 12

The preceding command instructs the debugger to remove the breakpoint that was set at line 12.

Appraisal   ◾    251

If no breakpoint is specified to be deleted, the debugger assumes one is defined for next line to execute and deletes it on its own. main::(debugtest:12):

&readsubdirs($vardir);

DB d

Because line 12 is the next line to be executed, the debugger automatically removes the breakpoint at line 12. The D-command is used to remove all of the program’s breakpoints. DB D

The above command removes all breakpoints set with the b command. Exiting from a Script Exit() evaluates the passed expression and exits the Perl interpreter, returning the value as the exit value. The exit() function does not always immediately exit but rather calls the program’s end routines before terminating it. If no expression is passed to exit function, the default value is 0. The exit() function has limited uses and should not be used to exit from a subroutine. To exit a subroutine, use die or return. Syntax: exit(value) Parameter: value which is to return on function call Returns: value passed to it or 0 if the function is called without an argument

Example: # Getting user's bid for # an online auction print "Enter bid"; $bid = ;

252   ◾    Appraisal # Exit function return $bid # if bid is less than 1000 if ($bid < 1000) { exit $bid; } else { # Prints message if the bid is # greater than or equal to 1000 print "\nThankyou for Participating"; }

Here’s how the code above works: • Step 1: Ask the user for a bid value. • Step 2: Exit returns the bid value and terminates the program if the bid is less than 1000. • Step 3: This message is printed if the bid is greater than or equal to 1000. Exit function parameter passing: A parameter can pass to the exit function and be stored in a variable in the system. It should note that the value passed to the exit function can be any random value; it does not have to be a specific value. The following example shows how to pass a value to the exit function: # Opening file if(!open(fh,"