📄 Page
1
(This page has no text content)
📄 Page
2
(This page has no text content)
📄 Page
3
Perl Programming for Beginners An Introduction to Learn Perl Programming with Tutorials and Hands-On Examples
📄 Page
4
Text Copyright © Lightbulb Publishing All rights reserved. No part of this guide may be reproduced in any form without permission in writing from the publisher except in the case of brief quotations embodied in critical articles or reviews. Legal & Disclaimer The information contained in this book and its contents is not designed to replace or take the place of any form of medical or professional advice; and is not meant to replace the need for independent medical, financial, legal or other professional advice or services, as may be required. The content and information in this book has been provided for educational and entertainment purposes only. The content and information contained in this book has been compiled from sources deemed reliable, and it is accurate to the best of the Author's knowledge, information, and belief. However, the Author cannot guarantee its accuracy and validity and cannot be held liable for any errors and/or omissions. Further, changes are periodically made to this book as and when needed. Where appropriate and/or necessary, you must consult a professional (including but not limited to your doctor, attorney, financial advisor or such other professional advisor) before using any of the suggested remedies, techniques, or information in this book. Upon using the contents and information contained in this book, you agree to hold harmless the Author from and against any damages, costs, and expenses, including any legal fees potentially resulting from the application of any of the information provided by this book. This disclaimer applies to any loss, damages or injury caused by the use and application, whether directly or indirectly, of any advice or information presented, whether for breach of contract, tort, negligence, personal injury, criminal intent, or under any other cause of action. You agree to accept all risks of using the information presented in this book. You agree that by continuing to read this book, where appropriate and/or necessary, you shall consult a professional (including but not limited to your doctor, attorney, or financial advisor or such other advisor as needed) before using any of the suggested remedies, techniques, or information in this book.
📄 Page
5
Table of Contents 1. Introduction 2. Scope of Perl How relevant is Perl in 2020 and beyond? What are the prerequisites of learning Perl? What will I learn from this book? 3. Getting Started 3.1 Installing Perl on Windows 3.2 Installing Perl on Unix-like systems 3.3 Perl Scripts/Programs 3.4 Script Execution 3.5 Hello World!!! Script Execution 4. Basic Syntax 4.1 Statements 4.2 Comments 4.3 Code Block 4.4 Identifiers 5. Writing your first Perl script 5.1 print Function 5.2 Syntax Errors 6. Data Types and Variables 6.1 Data Types 6.1.1 Scalar 6.1.2 Arrays 6.1.3 Hashes 6.2 Variables 6.2.1 Declaring Scalar Variables 6.2.2 Numeric Values 6.2.3 String Values 6.2.4 Display Scalar Variables
📄 Page
6
7. User Interaction 8. Operators 8.1 Arithmetic Operators 8.2 Assignment Operators 8.3 Comparison Operators 8.4 Logical Operators 8.5 Bitwise Operators 9. Decision Making 9.1 if-else Statements 9.2 unless Statement 10. Loops 10.1 while Loop 10.2 do-while Loop 10.3 until Loop 10.4 for Loop 10.5 Nested Loops 10.6 Control Statements 10.6.1 next Statement 10.6.2 last Statement 10.6.3 continue block 10.6.4 redo Statement 11. Arrays 11.1 Array Creation 11.2 Accessing Array Elements 11.3 Range Operator 11.4 Arrays and Loops 11.5 foreach Loop 11.6 Reading user input into arrays 11.7 Array Manipulation 11.8 Sorting Arrays
📄 Page
7
12. Hashes 12.1 Accessing and Manipulating Hashes 12.1.1 Check if a Key Exists 12.1.2 Delete Hash Elements 12.2 Fetch Keys and Values 13. Subroutines 13.1 Defining a Subroutine 13.2 Calling a Subroutine 13.3 Passing arguments 14. Strings 14.1 String Basics 14.2 String Concatenation and Repetition 14.3 Search within a string 15. File Handling 15.1 Basics of File I/O 15.1.1 Open Files 15.1.2 File Modes 15.1.3 Close Files 15.1.4 Create a simple file 15.1.5 Writing to a file 15.1.6 Reading from a file 15.1.7 Search text inside a file 16. Programming Examples 16.1 Prime or Composite 16.2 Fibonacci Series 16.3 Sum of digits of a number 16.4 Reverse a number 16.5 Menu driven program 16.6 Lowest Common Multiple 16.7 Search for an element in an array
📄 Page
8
16.8 Greatest element in an array 16.9 Bubble Sort 16.10 File Copy 17. Final Thoughts
📄 Page
9
1. Introduction Perl is a general purpose high level multi-paradigm programming language. In 1987, a computer programmer named Larry Wall began working on the development of Perl language at a company called Unisys and released the first version (version 1.0) on December 18, 1987 . Perl is actually a set of two programming languages – Perl 5 and Perl 6 . When we say just “Perl” , we refer to Perl 5 . In October 2019, Perl 6 was officially renamed to Raku . In this book, we well only focus on Perl 5 and refer to it as “Perl” . Although “Perl” does not stand for anything, there exist many unofficial acronyms including “Practical Extraction and Reporting Language” . Perl is a cross-platform interpreted language that works on over 100 platforms. Being an interpreted language, there is a Perl interpreter that sits on the host system which executes Perl programs/scripts. Some of the well- known Perl supported platforms are Windows, Linux, FreeBSD, MacOS, OpenVMS, Solaris, etc . It is possible to write a Perl program on one platform (say Windows) and take it to another platform such as Linux or Mac and execute it. The execution will go ahead seamlessly as Perl is a cross platform language. One exception to this feature is that your program should not contain any platform specific code. In case of programming languages such as C/C++ and Java, there is a compiler which compiles a program and generates executable code. Perl adopts a different approach when it comes to program execution – being an interpreted language, a Perl script is executed line by line by the Perl interpreter. C programming language is used to implement Perl environment. However, no knowledge of C is needed to learn Perl . Tools and languages such as AWK, BASIC, C/C++, sed, etc . have influenced Perl and languages such as JavaScript, CoffeeScript, Python, Ruby, PHP, etc . have been influenced by Perl.
📄 Page
10
2. Scope of Perl Perl is a general purpose scripting language and can be used for many things. You can build desktop applications, web applications, web services, GUI applications, etc. with it. There are powerful set of tools for text processing, file handling, regular expression and many more. These features led to Perl’s exponential growth and popularity in the 1990s and early 2000s. In 2020, Perl does not remain as popular as it used to be back in the day but is still a formidable language that can do a lot of things. In addition to the mentioned uses, Perl can be used to build network programming applications, scientific computing, system administration, etc. In fact, on Unix-like systems such as Linux, Mac and FreeBSD, system administrators use Perl to automate many tasks. Because of its power, flexibility and such diverse application space, Perl earned the nickname – “the Swiss Army chainsaw of scripting languages” . Another reason why Perl became so popular is because it emerged as the top choice for CGI (Common Gateway Interface) scripting . CGI is a web server interface between the end user and non-native web application. For example, a user can interact with a Perl script using a simple webpage with the help of CGI. All this cocktail of useful features, wide use cases, power and inelegance led to this language being referred to as – “duct tape that hold the internet together” . Database management is another powerful application of Perl. Databases such as MySQL, MSSQL, PostgreSQL, MongoDB, NoSQL, SQLite, etc. can be accessed and managed using Perl with the help of appropriate APIs. How relevant is Perl in 2020 and beyond? Since Perl is a general purpose, cross platform scripting language, it can be used to build applications and solve problems across many domains and platforms. Amazon uses Perl for most of its backend. There is a Perl based web framework called catalyst which powers DuckDuckGo search engine’s community edition and BBC iPlayer’s backend. Apart from catalyst, there are some more web frameworks such as Mojolicious , Perl Dancer , etc. which power thousands of websites, web applications and web services. A well-known SPAM filter called SpamAssasin is written in Perl. For developing GUI applications, there are bindings available of several cross
📄 Page
11
platform GUI frameworks such as PerlQt (for Qt), PerlTk (for Tk), wxPer (for wxWidgets), etc . What are the prerequisites of learning Perl? If you already know programming languages such as C/C++, Python, Java, C#, etc. it will help you a great deal in learning Perl. If you do not, there is no need to worry as Perl is an easy to understand programming language. However, you should be comfortable with using your system and be well versed with using Shell/Terminal on Linux/MAC and Command Prompt/PowerShell on Windows. What will I learn from this book? Once you have gone through the whole book, you will be able to write simple command line based desktop applications that can do various things. This will set the base for learning advanced concepts. Perl is an incredibly powerful language for developing web applications. Learning web programming using Perl is pointless without understanding core web development technologies such as HTML5, CSS, JavaScript and hence web application development using Perl has not been covered in this book.
📄 Page
12
3. Getting Started A PC/Laptop with Windows/Linux or a MAC system is needed to write and execute Perl scripts/programs. Perl programs can be written using any text editor including Notepad, Wordpad, vi, etc. I suggest Notepad++ (https://notepad-plus-plus.org/ ). Simple Perl scripts are plain-text files and carry the extension .pl . Other extensions of Perl file types are – .pm, .xs, .t, .pod . We will only be working with the .pl file type. As mentioned earlier, a Perl interpreter is responsible for executing Perl scripts. In this chapter, we will learn how to install Perl Interpreter. 3.1 Installing Perl on Windows There are two major Perl implementations for Windows – ActiveState Perl and Strawberry Perl . Both implementations are official and using either one is fine for a beginner. We will be using Strawberry Perl to work with Perl scripts through the course of this book. You can choose to go ahead with ActiveState Perl should you so desire. Log on to https://www.perl.org/get.html and download the Perl interpreter of your choice. Here is how you set up Strawberry Perl on your Windows system: Execute the installation binary. You will need Administrator rights to do so. You will be greeted with a welcome screen that looks like this:
📄 Page
13
Click Next, you will be presented with the EULA:
📄 Page
14
Read the agreement, accept the terms and click Next. Here, you will be given an option to choose the installation directory. It is best to leave this unchanged unless you are an advanced user and you know what you are doing. Click Install in the next Window.
📄 Page
15
The setup process will now begin and will take a few minutes.
📄 Page
16
Once the installation is complete, you will see something like this: Now, open Command Prompt/PowerShell , type perl -v and hit Enter . You should see Perl’s version and some more information like this: If you see an error message like – “perl” is not recognized as an internal or external command, operable program or batch file , it means either Perl has not been properly installed or the PATH variable has not been properly set. In such a case, make sure that Strawberry Perl has been installed by going to the installation directory (C:\Strawberry in case you did not change it during installation process). Navigate to
📄 Page
17
<drive>:\Strawberry\Perl\bin directory, make sure there is an executable called perl.exe . If it does not exist, re-install Strawberry Perl. If it does exist, add <drive>:\Strawberry\Perl\bin to your environment variable PATH by going to System Properties . 3.2 Installing Perl on Unix-like systems If you use a Unix-like system such as Linux, MAC, FreeBSD, etc., it is likely that Perl environment is already present on your system. The best way to check is – open the Shell/Terminal and enter the following command at the prompt: $>perl -v This command will display Perl’s version if it is present and you should see something like this: If Perl is not present, you will see an error message. In such a case, go to https://www.perl.org/get.html , download and install the appropriate version of Perl for your operating system. 3.3 Perl Scripts/Programs A Perl script is a plain-text file containing instructions which can be written using any text editor or a supported IDE. To keep things simple, I prefer using Notepad++ . A script once written should be saved with the extension .pl . This file is referred to as – Perl script, Perl program, Perl source, source code, source file or simply script/ program/source.
📄 Page
18
Writing Perl scripts on Windows is straight forward. Just open your favourite text editor, start writing the script and save it as <file name>.pl . On Unix-like systems such as Linux, MAC, FreeBSD, etc., you have to one extra thing – add a shebang line . A shebang line is a sequence of characters beginning with #! followed by the location of the environment or the script interpreter. In our case, it is the Perl interpreter. This line should be the first one in your script. The Perl interpreter is usually located at /usr/bin/perl or /usr/local/perl . Hence, on Unix-like systems, the shebang line will look like: #!/usr/bin/perl #OR #!/usr/local/perl A good way to determine the location of the Perl interpreter is to use the where or locate command on Linux as follows: $>where perl OR $>locate perl On MAC, you can use the which command: $>which perl These commands will return the location of the Perl interpreter, simply copy it and use it as a part of your shebang like. Note: A shebang line is not always required but is considered as a good programming practice. Hence, I suggest you always insert this line in your Perl scripts on Linux/MAC. We will look at a condition where the shebang is always required later in this chapter. 3.4 Script Execution A Perl script can be executed on Windows and Unix-like systems by invoking the Perl interpreter using the perl command inside the Command Prompt/Powershell or Terminal/Shell. When we say perl command, it refers to the Perl interpreter’s executable binary which is perl.exe on Windows (present at Perl’s installation directory, eg. C:\Strawberry\perl\bin\perl.exe) and /usr/bin/perl or any other appropriate location of the Perl interpreter on Unix-like systems. The script to be executed should be passed as a
📄 Page
19
command line argument to this command as follows using Command Prompt/Powershell or Terminal/Shell: perl <script name> Example: perl myscript.pl In the above example, the Perl interpreter will start executing myscript.pl Perl script. It goes without saying that the script to be executed should be present in the current working directory. Alternatively, you can provide the complete path of the script file. There is another method of executing scripts on Unix-like systems. That is by making the script itself executable. In Linux, MAC, FreeBSD, etc. there are 3 file permissions – read, write and execute . This is a vast topic and covering it is beyond the scope of this book. What we are interested in is the execute permission. A script can be made executable by giving it the execute permission. To do so, we have to use the chmod command. In order to give execute permission to a file, we use the +x flag with the chmod command. General Syntax: chmod +x <file 1>, <file 2>, … , <file n> Example: chmod +x demo.pl chmod +x myscript.pl, yourscript.pl, ourscript.pl Once this permission has been given to a script, it can be executed as: ./<script name> Example: ./myscript.pl Note: When a script is made executable, it is mandatory to have a shebang line pointing to the environment or the location of the Perl interpreter . Without this line, the script will not execute as it will not know which interpreter to invoke in order to begin script execution. 3.5 Hello World!!! Script Execution Let us get hands-on experience in executing a Perl script. Open the text editor of your choice, copy-paste the following code and save it as helloworld.pl at a convenient location:
📄 Page
20
#This is a simple Hello World Perl Script. #Uses print function to display text on the console. print ( "\nHello World!!!\n\n" ); Side Note: You do not have to understand the code for now, we are only learning how to execute a script. Let us execute this script first on Windows and then move to Unix-like systems. Open Command Prompt/PowerShell , navigate using the cd command to the directory where helloworld.pl has been saved. Enter the following command: perl helloworld.pl You should see the output as follows: If you use Unix-like systems, modify the above code by adding the shebang line pointing to the Perl interpreter. For demonstration purpose, I am using Debian Linux and this is what my code looks like: This script can be executed on Unix-like systems in two ways – by invoking the Perl interpreter and by making the script itself executable. Let us look at the Perl interpreter invocation first. Open Shell/Terminal, navigate to the directory where helloworld.pl has been saved and enter the following command: