Beginning Perl
Programming
Self-Study Guide &
Student Manual
2018-19
Edition
William "Bo" Rothwell
A publication by
Copyright One Course Source, 2018 ALL RIGHTS RESERVED
This publication contains proprietary and confidential information, which is the property of One Course Source, Inc. No part of this publication is be reproduced, copied, disclosed, transmitted, stored in a retrieval system or translated into any human or computer language, in any form, by any means, in whole or in part, without the prior express written consent of One Course Source.
THIS PUBLICATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
REFERENCES TO CORPORATIONS, THEIR SERVICES AND PRODUCTS, ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED. IN NO EVENT SHALL ONE COURSE SOURCE BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ARISING OUT OF OR IN CONNECTION WITH THE USE OF THIS INFORMATION.
Descriptions of, or references to, products or publications within this publication do not imply endorsement of that product or publication. One Course Source makes no warranty of any kind with respect to the subject matter included herein, the products listed herein, or the completeness or accuracy of this publication. One Course Source specifically disclaims all warranties, express, implied or otherwise, including without limitation, all warranties of merchantability and fitness for a particular purpose.
THIS PUBLICATION COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN; THESE CHANGES WILL BE INCORPORATED IN NEW EDITIONS OF THE PUBLICATION. ONE COURSE SOURCE MAY MAKE IMPROVEMENTS AND/OR CHANGES IN THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED IN THIS PUBLICATION AT ANY TIME.
Table of Contents ©2018 One Course Source, Inc. Page 3 Module Table
of Contents
Introduction
Unit One Meet Perl Page
1.1 ... Origin of Perl 16 1.2 ... Perl development environments 17 1.3 ... Perl Versions 21 1.4 ... Invoking Perl 24 1.5 ... Perl Documentation 30 1.6 ...Perl Resources 36 1.7 ...Lab Exercises 37
Table of Contents ©2018 One Course Source, Inc. Page 4 Unit Three Array Variables Page
3.1 ... Array Variables 74 3.2 ... Referencing Array Elements 75 3.3 ... Adding & removing elements in an array 79 3.4 ... The splice function 82 3.5 ... Using for loops 85 3.6 ... Using foreach loops 87 3.7 ... The reverse statement 91 3.8 ... The sort operator 92 3.9 ... The qw and qq statements 95 3.10 ... Arrays used in scalar context 96 3.11 ... Additional Resources 97 3.12 ...Lab Exercises 98
Table of Contents ©2018 One Course Source, Inc. Page 5 Unit Five Flow Control Page
5.1 ... Blocks 126 5.2 ... The if Statement 127 5.3 ... The unless Statement 133 5.4 ... The switch statement 134 5.5 ... The given statement 137 5.6 ... The while Statement 139 5.7 ... The until Statement 173 5.8 ... The do Statement 141 5.9 ... Loop control: last 144 5.10 ... Loop control: next 148 5.11 ... Additional Resources 149 5.12 ...Lab Exercises 150
Table of Contents ©2018 One Course Source, Inc. Page 6 Unit Seven Basic Input and Output Page
7.1 ... Reading Input 176 7.2 ... while & until Loops 177 7.3 ... Record Separator Variable 179 7.4 ... The Diamond Operator 181 7.5 ... The Default Variable 184 7.6 ... Using parentheses 186 7.7 ... Additional Resources 187 7.8 ...Lab Exercises 188
Unit Eight Advanced Input and Output Page 8.1 ... Filehandles 190 8.2 ... The die and warn Statements 191 8.3 ... Opening and Reading from Files 195 8.4 ... Opening and Writing to Files 198 8.5 ... Reading a Block of a Filehandle 200 8.6 ... Reading a Single Character 202 8.7 ... Piping in Perl 203 8.8 ... The format Statement 207 8.9 ... Here Documents 219 8.10 ... Additional Resources 222 8.11 ...Lab Exercises 223
Table of Contents ©2018 One Course Source, Inc. Page 7 Unit Ten Perl Utilities Page
10.1 ... split 266 10.2 ... join 270 10.3 ... substr 272 10.4 ... index 275 10.5 ... rindex 276 10.6 ... grep 278 10.7 ... srand & rand 280 10.8 ... sleep 282 10.9 ... Additional Resources 284 10.10 ...Lab Exercises 285
Unit Eleven Filesystem & Process Control Page 11.1 ... Controlling the Filesystem within Perl 287 11.2 ... Working with Directories 289 11.3 ... Working with Files 294 11.4 ... Back-Quoting 298 11.5 ... The System Statement 299 11.6 ... Additional Resources 301 11.7 ...Lab Exercises 302
Table of Contents ©2018 One Course Source, Inc. Page 8 Unit Thirteen Using Modules Page
13.1 ... What are Modules? 327 13.2 ... Loading Modules with use 328 13.3 ... Other functions of use 330 13.4 ... Additional Resources 335 13.5 ...Lab Exercises 336
Introduction ©2018 One Course Source, Inc. Page 9 Introduction
About this course
This manual was designed with the goal of assisting instructors in their efforts of teaching students to be able to create Perl programs.
Typographical syntax
Examples in this text of commands will appear in bold text and the output of the commands will appear in italic text. The commands and the output of the commands will be placed in a box to separate them from other text. Example:
[student@ocs student]$ pwd
/home/student
Note: "[student@ocs student]$" is a prompt, a method the shell uses to
say “I’m ready for a new command”.
Introduction ©2018 One Course Source, Inc. Page 10 Using this manual while in class
In many ways, class manuals are different from textbooks. Textbooks are often filled with lengthy paragraphs that explain a topic in detail.
Unfortunately, this style doesn’t work well in a classroom environment.
Class manuals often are much more concise than textbooks. It's difficult to
follow the instructor’s example and read lengthy paragraphs in a book at
the same time. For this purpose, class manuals are often more terse.
Lab Exercises
Introduction ©2018 One Course Source, Inc. Page 11 Resources
In each unit, resources are provided to provide the learner with a source for more information. These resources may include online documentation, local (on your system) documentation and traditional books.
Due to the fact that these resources changes (especially online resources), we provide these resources on our web site instead of printing them in our courseware. This allows us to provide updated resources in a timely
manner.
For this class, the resources can be found here:
Introduction ©2018 One Course Source, Inc. Page 12 Using the Perl debugger
During this course the Perl debugger is used to demonstrate techniques. To enter the Perl debugger to test Perl code, use the following:
ocs% perl -d -e "1;"
Loading DB routines from perl5db.pl version 1.32 Editor support available.
Enter h or `h h' for help, or `perldoc perldebug' for more help.
main::(-e:1): 1;
DB<1>
Note: if you installed Active State's ActivePerl, you might end up in their GUI-based debugger. To temporarily change your system to use the built-in Perl debugger, enter the followbuilt-ing command(s) built-in your shell:
Windows
Introduction ©2018 One Course Source, Inc. Page 13 Linux
export PERLDB_OPTS=
To re-enable the PDK debugger, set the PERL5DB variable to an empty string.
A note about this course content
In most cases it is best to use the latest version of Perl. However, using the latest version is not always going to be possible. Many students who follow this course or take official OCS classes will be in an environment that uses an older versions of Perl (sometimes a much older version). There are a variety of reasons (being stuck on an older OS platform, needing a feature that only exists in an older version of Perl, stubborn IT managers, etc.) why you may be required to use an older version of Perl.
This was taken into consideration when this manual was written. While the newer Perl techniques are covered in this class and are normally more effective, the course also presents older techniques. Not only does this help support Perl programmers who are stuck in older versions of Perl, but it also helps Perl programmers who have been called upon to maintain (or update) older Perl scripts.
In addition, there are many things in Perl that can be accomplished in more than one way. While not every single method is provided in this course, we do try to show different common ways of performing tasks. This makes it easier for you to read other Perl scripts that may have used a different technique than what you are using.
Introduction ©2018 One Course Source, Inc. Page 14
Try it!
Throughout the course, you will see boxes like this one. The purpose of these boxes is to encourage you to try a new skill that is being taught.
1 – Perl Fundamentals ©2018 One Course Source, Inc. Page 15 Unit One
Meet Perl
Unit topics: Page
1 – Perl Fundamentals ©2018 One Course Source, Inc. Page 16 1.1 Origin of Perl
1 2
Perl was developed in 1987 by Larry Wall. It was created because the 3
tools that were available to Mr. Wall at the time (sed, C, awk and the 4
Bourne Shell) didn’t provide the sort of functionality that he required.
5 6
Perl was initially called Pearl, but the name was quickly changed due to the 7
fact that there was another language called Pearl at the time. Perl is a 8
backronym (a constructed acronym created to fit an existing word) that 9
stands for "Practical Extraction & Report Language”. Some programmers 10
(typically those who don’t like Perl) claim that Perl stands for
11
"Pathologically Eclectic Rubbish Lister". 12
13
Perl code is mostly machine-independent. This means that you can write a 14
Perl program on one platform (like Linux) and then easily use the same 15
program on another platform (like Windows). When dealing directly with 16
the Operating System or filesystem, you may need to make some changes 17
to your code. 18
19
Perl has been ported to UNIX, Windows, Linux and many others (see 20
http://www.cpan.org/ports for a complete list). 21
1 – Perl Fundamentals ©2018 One Course Source, Inc. Page 17 1.2 Perl development environments
1 2
In some cases you might not have a choice as to which platform or 3
derivative of Perl that you will use to develop your code. However, if you 4
do have a choice, you should spend some time learning the differences 5
between your options. 6
7
*nix/Windows 8
9
*nix refers to any UNIX-based OS (including Linux). Many developers 10
prefer this environment over Windows for several reasons, including: 11
12
• UNIX-based systems typically have more powerful features for 13
developers. For instance, most UNIX-based systems have a C or 14
C++ compiler, making it easier to install CPAN modules. Windows 15
systems typically don't have a C/C++ compiler by default. 16
• UNIX-based systems tend to be more stable than Window-based 17
systems. 18
19
There are other advantages (and some would argue there are advantages 20
of Windows over *nix). Consider the pros and cons of each before 21
deciding your development platform. 22
23
In either case, if you are worried about writing portable code, you probably 24
want to review the following document: 25
http://perldoc.perl.org/perlport.html. 26
1 – Perl Fundamentals ©2018 One Course Source, Inc. Page 18 Which derivative for *nix?
1 2
If you decide to develop on a UNIX-based platform, you may want to 3
consider which derivative of Perl to install and develop on. Unless you 4
want to create a custom build of Perl (well beyond the scope of this class*), 5
your choice will likely come down to two: the standard Perl derivative 6
(www.perl.org) or ActiveState's ActivePerl 7
(http://www.activestate.com/activeperl). 8
9
When you consider which derivative to use, take the following into account: 10
11
• Most *nix systems have Perl installed by default as several system 12
tools (especially on Linux) make use of Perl to manipulate data. In 13
these cases, you are likely to find the standard Perl installed (or a 14
custom build for that Linux distribution). 15
• ActivePerl comes with a tool to easily install Perl modules: ppm. 16
This tool is normally considered easier to use than installing CPAN 17
modules with the -MCPAN option. 18
• ActivePerl's ppm doesn't install modules directly from CPAN, but 19
rather from another repository that ActiveState maintains. This 20
means you have access to a subset of the CPAN modules, not the 21
complete set. Note: you can choose additional repositories by 22
clicking "Edit" + "Preferences" and choosing the "repositories" tab. 23
24
*If you do want to create your own custom Perl derivative, you probably 25
want to start by looking at the following: http://search.cpan.org/dist/App-26
perlbrew/. 27
1 – Perl Fundamentals ©2018 One Course Source, Inc. Page 19 Which derivative for Windows?
1 2
If you are working on a Window's platform, you have a few choices 3
available, as described on www.perl.org: 4
5
• ActiveState Perl has binary distributions of Perl for Win32 (and Perl 6
for Win64). 7
• Strawberry Perl: A 100% Open Source Perl for Windows that is 8
exactly the same as Perl everywhere else; this includes using 9
modules from CPAN, without the need for binary packages. (see 10
http://strawberryperl.com/) 11
• DWIM Perl for Windows: A 100% Open Source Perl for Windows, 12
based on Strawberry Perl. It aims to include as many useful CPAN 13
modules as possible. It even comes with It even comes with Padre, 14
the Perl IDE. (see http://dwimperl.com/windows.html) 15
16
A few things to consider: 17
18
• ActivePerl has ppm, Strawberry Perl does not. However, Strawberry 19
Perl has many CPAN modules installed by default (both a pro and a 20
con). 21
• With ActivePerl you can get official support. Strawberry Perl provides 22
only community support. 23
• Strawberry Perl comes with gcc, a C/C++ complier, making it easier 24
to install modules from CPAN. 25
• Strawberry Perl release cycle tends to be slower than ActivePerl. 26
• "When I'm on Windows, I use Strawberry Perl." - Larry Wall 27
1 – Perl Fundamentals ©2018 One Course Source, Inc. Page 20 Pick your Perl development tools
1 2
There are several good tools to help you develop your Perl code. This 3
includes debuggers, editors and IDEs. Some of these tools are free, some 4
can be very expensive. Many of them are community support while a few 5
are commercially supported. 6
7
A good place to start exploring these tools is the following web site: 8
http://www.perlmonks.org/?node_id=531175 9
1 – Perl Fundamentals ©2018 One Course Source, Inc. Page 21 1.3 Perl versions
1
To verify Perl is installed, and to show the version, type the command perl 2
-v: 3
4
[student@ocs student]$ perl -v 5
6
This is perl, v5.10.1 built for MSWin32-x86-multi-thread
7
(with 4 registered patches, see perl -V for more detail)
8 9
Copyright 1987-2009, Larry Wall
10 11
Binary build 1008 [294165] provided by ActiveState
12
Perl may be copied only under the terms of either the Artistic License or
16
the
17
GNU General Public License, which may be found in the Perl 5 source kit.
18 19
Complete documentation for Perl, including FAQ lists, should be found on
20
this system using "man perl" or "perldoc perl". If you have access to the
21
Internet, point your browser at http://www.perl.org/, the Perl Home Page.
22 23
You will see by the highlighted section above that Perl 5.10.1 is used on 24
this system. As of the date of when this was written, this version is 25
considered a bit "old", however it is important to note that many Perl 26
developers are still using older versions of Perl. They may be "stuck" with 27
an older version because of platform issues or "related" software issues. 28
This manual isn't written for a specific version of Perl 5, however notes will 29
be made when a "newer" concept is covered. 30
31
Perl 5.10.1 is specifically used in this course because of a change that 32
took place in that version. 33
1 – Perl Fundamentals ©2018 One Course Source, Inc. Page 22 Understanding Perl versions
1 2
Perl version numbers sometimes are confusing. The first version of Perl 5 3
(5.000) was released in 1994. Initially Perl version numbers following the 4
numbering convention of 5.000, 5.001, 5.002, etc. When a minor change 5
or "bug fix" release occurred, the numbering included this as 5.002_001 or 6
5.002_002. 7
8
The last release that followed this convention was 5.005_63; the next 9
release was 5.6.0. The primary reason for this numbering change was to 10
fall in line with the version numbering system that most Open Source 11
projects followed. 12
13
Additionally, odd number releases (5.7, 5.9, 5.11, etc.) are considered 14
development releases and should not be used for "real" programming. 15
Which version of Perl 5 should you use? In some cases you may not have 26
a choice as your organization may have a specific version of Perl that you 27
must use. However, if the choice is yours, consider the following: 28
29
• Newer versions have more features than older versions. 30
• Only the latest version and the previous production release are 31
supported. Any older version is no longer actively maintained. 32
33
This course was specifically written to address subtle differences in 34
different Perl 5 versions. Most of the material should work fine in Perl 5.6 35
and higher. When there are differences, they will be mentioned in the 36
course materials. 37
38
Previous release: 5.005_63
Development releases Production releases
1 – Perl Fundamentals ©2018 One Course Source, Inc. Page 23
Try it!
1 2
Whenever you program in Perl, it is very helpful to know what version of 3
Perl you are using. Execute the following command to determine the 4
version of Perl that you are currently using: 5
6
perl –v
1 – Perl Fundamentals ©2018 One Course Source, Inc. Page 24 1.4 Invoking Perl
1 2
There are three methods to invoke Perl: the command line method, the 3
interactive method and the script method. 4
5
The command line method 6
7
Although this method is the least common way of invoking Perl, it does 8
provide a means of "testing" simple Perl statements. The -e option allows 9
the user to enter the Perl statements on the command line: 10
11
[student@ocs student]$ perl -e 'print "This is my first perl program\n";' 12
This is my first Perl program
13 14
Notes: 15
16
➢ The print statement will display its arguments to STDOUT (standard 17
output, usually the screen) 18
19
➢ The "\n" character represents a newline character 20
21
➢ The ";" character ends the print statement 22
23
➢ The single quotes around the Perl statement are needed to "protect" 24
special characters from the shell 25
26
➢ The double quotes are needed around the text that will be printed by 27
the print statement 28
29
➢ In the Win32 environment, use double quotes around the print, 30
single around the text. 31
1 – Perl Fundamentals ©2018 One Course Source, Inc. Page 25 The interactive method (debugger)
1 2
The interactive method makes use of the Perl debugger to allow you to 3
enter a Perl "shell" in which you can type Perl statements. This is useful 4
not only for testing Perl scripts, but also for "interactively" testing Perl 5
statements. 6
7
To enter the Perl debugger, use the -d option: 8
9
[student@ocs student]$ perl -d -e "1;" 10
➢ The -e option allows you to enter the Perl statement(s) on the 15
command line. The "1;" is a "dummy" statement that has no real 16
meaning (but provides Perl with valid code in order to enter the 17
debugger). 18
19
➢ Instead of specifying -e "1;" you could specify a script name to 20
debug the script. 21
22
➢ Many of the examples given in this course are performed within the 23
debugger. This allows the instructor to demonstrate a concept or 24
technique without having to create a full program. 25
26
➢ There are a (very) few statements/features that don't work in the Perl 27
debugger. 28
1 – Perl Fundamentals ©2018 One Course Source, Inc. Page 26 Note: if you installed Active State's ActivePerl, you might end up in their 1
GUI-based debugger. To temporarily change your system to use the built-2
in Perl debugger, enter the following command(s) in your shell: 3
4
Windows 5
6
set PERL5DB=BEGIN { require 'perl5db.pl'; } 7
set PERLDB_OPTS= 8
9
Linux 10
11
export PERLDB_OPTS= 12
13
To re-enable the PDK debugger, set the PERL5DB variable to an empty 14
string. 15
1 – Perl Fundamentals ©2018 One Course Source, Inc. Page 27
Try it!
1 2
Execute the following command to enter the Perl Debugger environment: 3
4
perl –d –e “1;”
5 6
At the debugger prompt, execute the following Perl statement: 7
8
print 5 + 6;
9 10
Exit the debugger by executing the following Perl statement: 11
12
quit
1 – Perl Fundamentals ©2018 One Course Source, Inc. Page 28 The script method
1 2
This method is the most common method; it allows you to place Perl 3
statements inside of a file and execute them. The following line of text can 4
be placed into a file: 5
6
#1_first.pl 7
print "This is my first Perl program\n "; 8
9
And then executed by using the Perl command: 10
11
[student@ocs student]$ perl 1_first.pl 12
This is my first Perl program
13
[student@ocs student]$ 14
15
Note: 16
➢ The "#" character is for commenting. 17
1 – Perl Fundamentals ©2018 One Course Source, Inc. Page 29 UNIX-based operating systems provide you another method of executing 1
the script. You can place a special line of code at the top of the script 2
called a "shbang" (or "shebang") that tells the OS which command to use 3
to execute the script. 4
5
The first line in the following script is the shbang. It must start with "#!" and 6
then contain the path to the command that will execute the script: 7
8
#!/usr/bin/perl 9
# 1_second.pl 10
print "This is my second Perl program\n "; 11
12
Now that the shbang has been added, just make the script executable and 13
run it like a program: 14
15
[student@ocs student]$ chmod a+x 1_second.pl 16
[student@ocs student]$ ./1_second.pl 17
This is my second Perl program
18
[student@ocs student]$ 19
20
Notes: 21
22
➢ On a Windows system the shbang is primarily treated as a comment 23
(unless you use #!perl followed by an option to Perl). The Win32 24
environment uses file extension association (associating the “.pl”
25
extension with the Perl Command Line Interpreter). 26
27
➢ The actual location of Perl may vary from one platform to another. 28
The rest of the example in this course will use #!perl instead of 29
1 – Perl Fundamentals ©2018 One Course Source, Inc. Page 30 1.5 Perl Documentation
1 2
One of the great features of Perl is the quality of its documentation. This 3
documentation can be accesses from several different sources. One of 4
these sources is the web site perldoc.perl.org. While browsing this site, 5
there are a few things that you want to take into consideration: 6
7 8 9 10 11 12
13
Each version of Perl will have different
documentation. Be sure to select the version you are working on.
General information regarding Perl is found under the "Manual" section.
When you want to view documentation about a specific function, variable or feature, look under the Reference section.
1 – Perl Fundamentals ©2018 One Course Source, Inc. Page 31 In addition to the web-based documentation, you can access
1
documentation on your one system. If you are working on UNIX or Linux, 2
you can execute the command man perl: 3
4
5 6
Press the "ENTER" key to scroll down one line at a time, the "space bar" 7
key to scroll down one page at a time and the "q" key to quit viewing the 8
document. 9
1 – Perl Fundamentals ©2018 One Course Source, Inc. Page 32 On Windows, execute the command perldoc perl:
1 2
3 4
Note: you can also execute the perldoc command on UNIX and Linux 5
systems, however the man command doesn't exist on Windows systems 6
(unless additional software is installed). 7
1 – Perl Fundamentals ©2018 One Course Source, Inc. Page 33 If you review the main documentation page (perldoc perl), you will discover 1
many other useful sub-catagories. The following highlights a few that you 2
many consider taking the time to read through: 3
4
Document Description 5
perlintro Perl introduction for beginners 6
perlrequick Perl regular expressions quick start 7
perlretut Perl regular expressions tutorial 8
perlstyle Perl style guide 9
perlcheat Perl cheat sheet 10
perltrap Perl traps for the unwary 11
perldebtut Perl debugging tutorial 12
perlsyn Perl syntax 13
14
Each of these can be viewed by either using the man command or the 15
perldoc command. For example, to see the Perl cheat sheet, execute the 16
perldoc perlcheat command. 17
1 – Perl Fundamentals ©2018 One Course Source, Inc. Page 34
Try it!
1 2
Execute the following command to display the “perl style guide”: 3
4
perldoc perlstyle
1 – Perl Fundamentals ©2018 One Course Source, Inc. Page 35 To see documentation on a specific builtin function, use the -f option with 1
the perldoc command. For example, to view the documentation for the 2
Perl print function, execute perldoc -f print: 3
4
1 – Perl Fundamentals ©2018 One Course Source, Inc. Page 36 1.6 Perl Resources
In each unit, resources are provided to provide the learner with a source for more information. These resources may include online documentation, local (on your system) documentation and traditional books.
Due to the fact that these resources changes (especially online resources), we provide these resources on our web site instead of printing them in our courseware. This allows us to provide updated resources in a timely
manner.
For this unit, the resources can be found here:
1 – Perl Fundamentals ©2018 One Course Source, Inc. Page 37 1.7 Lab Exercises
A note about the lab exercises in this class: Creating lab exercises that will be beneficial to all students can be difficult. Lab exercises that focus on specific scenarios (such as engineering test cases) can result in
difficulties for students who do not perform this sort of programming. As a result, we focused on creating labs that will perform tasks that are fairly generic, but that also assist the student in practicing the new skills that are learned in class. In addition, to make the lab exercises more realistic, we attempt to build on one script throughout class rather than build many, small scripts.
Throughout this course, you will build on a script called "cb.pl"
This script will eventually be a simple (flat) database program that will be customized to fit simple database needs. To make it specific for the class, we will make it a database that contains checkbook entries.
For this lab, create a file called cb1.pl and perform the following functions:
1. Create comments at the beginning of the code that indicate what the program does (handles deposits, withdrawals, checks writing, looks up checks by check number or date written, and prints a statement) and other data (author, date/time, version (1.1))
2. Using the print statement, have the program produce the following output when it is run:
Welcome to checkbook 1.1 Please enter your name:
When you have completed your work, compare your script against the cb1.pl file provided in lab answers. During the instructor-led classes, the instructor may review the answer script and provide you with the
2 – Scalar Variables ©2018 One Course Source, Inc. Page 38 Unit Two
Scalar Variables
Unit topics: Page
2 – Scalar Variables ©2018 One Course Source, Inc. Page 39 2.1 Numeric Literals
1 2
A numeric literal is simply any kind of valid number. In Perl the following 3
numeric types are supported: 4
While it's important to know what numeric types Perl supports, it's also 12
important to understand that Perl doesn't "treat" these types differently. In 13
fact, all numbers (and strings) are considered to be of one type in Perl: 14
scalar. 15
16
Also note that while you can represent scalar values as Hex, Octal or 17
Scientific, Perl will really treat them as integer values: 18
Scalar data is "a single value". This could be any of the above numeric 27
“formats” or any string (strings are discussed in section 2.3).
2 – Scalar Variables ©2018 One Course Source, Inc. Page 40 2.2 Manipulating Numbers
1 2
There are three basic types of operations you can perform on numbers: 3
mathematical, predefined functions and comparison. Numeric comparison 4
will be discussed a later unit when all types of comparisons are covered. 5
6
Mathematical operations 7
8
Perl allows the following mathematical operations: 9
10
Operation Symbol Example Result/Notes
Addition + 6+5 11
Note: The auto increment and auto decrement
2 – Scalar Variables ©2018 One Course Source, Inc. Page 41 Pre-defined functions
1 2
Perl has some useful pre-defined functions that can be used to manipulate 3
numbers (More modern versions of Perl also support trigonometry 4
functions such as sin and cos): 5
6
Operation Function Example Result Absolute value abs abs(-101) 101 Convert hex to
integer
hex hex("f0") 240
Integer value int int(12.98) 12 Convert octal to
integer
oct oct("0570") 376
Generate random (floating point) number
rand rand(10) varies depending upon random seed
Square root sqrt sqrt(100) 10
DB<1> print hex("e2") 10
226
11
DB<2> print int(101.02) 12
101
13 14
Note: The rand and srand functions are discussed in detail in a later unit. 15
2 – Scalar Variables ©2018 One Course Source, Inc. Page 42
Try it!
1 2
Execute the following command to enter the Perl debugger: 3
4
perl –d –e “1;”
5 6
Execute the following commands in the Perl debugger to practice math 7
operations: 8
9
print 5 * 5;
10
print 10 / 0;
11
print sqrt(9);
12 13
Exit the Perl debugger by executing the following debugger command: 14
15
quit
2 – Scalar Variables ©2018 One Course Source, Inc. Page 43 2.3 String Literals
1 2
A string literal is a set of characters that have quotes (double or single) 3
surrounding them. Some examples of strings: 4
5
"a is the first letter of the alphabet" 6
"John is late for work" 7
'Perl is the best programming language in the world' 8
9
Notes: 10
11
➢ There is a difference between single and double quotes which will be 12
discussed in a later section. 13
14
➢ Even though strings are created by placing quotes around 15
characters, it is important to note that what really makes something a 16
string is the function or operator that is performed on the value. This 17
will be covered in greater detail in a later section in this unit. 18
2 – Scalar Variables ©2018 One Course Source, Inc. Page 44 2.4 Manipulating Strings
1 2
As with numbers, there are three basic types of operations you can 3
perform on strings: alteration operators, predefined functions and 4
comparison operators. String comparison will be discussed in a later unit 5
when all types of comparisons are discussed. 6
7
Alteration operators 8
9
There are two alteration operations you can perform on strings. 10
11
Operation Symbol Example Result Concatenate . "abc"."def" abcdef
Repeat x "abc"x5 abcabcabcabcabc 12
Why use the x operator? Consider the following example: 13
14
DB<1> print "-" x 30, "\n", "Name: Bob Smith\n", "-" x 30 15
---
16
Name: Bob Smith
17
---
2 – Scalar Variables ©2018 One Course Source, Inc. Page 45 Pre-defined functions
1 2
Operation Function Example Result Delete new line character
at end of string
chomp See later section in this unit
N/A
Delete last character of string
chop See later section in this unit
N/A
Return index of substring index or rindex
See later unit N/A
Merge multiple strings together
join See later unit N/A
Turn all CAPS to lower case
lc lc("HELLO") hello
Turn first char to lower case
lcfirst lcfirst("HELLO") hELLO
Returns the length of the string
length length("abc") 3
Break string into elements (array)
split See later unit N/A
Returns a substring of a string
substr See later unit N/A
Turn all lower case to CAPS
uc uc("hello") HELLO
Turn first char to CAPS ucfirst ucfirst("hello") Hello 3
Notes: 4
5
➢ chomp and chop will be discussed in more detail in a later section of 6
this unit because they are more commonly used on variables, not 7
string constants. 8
9
➢ index, rindex, join, split and substr will are discussed in a later 10
unit. 11
2 – Scalar Variables ©2018 One Course Source, Inc. Page 46
Try it!
1 2
Execute the following command to enter the Perl debugger: 3
4
perl –d –e “1;”
5 6
Execute the following commands in the Perl debugger to practice string 7
operations: 8
9
print “Bob” . “Smith”;
10
print “Bob” . “ “ . “Smith”;
11
print length(“Bob”);
12 13
Exit the Perl debugger by executing the following debugger command: 14
15
quit
2 – Scalar Variables ©2018 One Course Source, Inc. Page 47 The importance of using quotes
1 2
Perl is often referred to as a "lazy" programming language as it sometimes 3
allows you to omit some syntax. For example, consider the following code: 4
In the previous code, the value of red should have had quotes around it. 10
However, it seems to have worked just fine without the quotes. 11
Unfortunately, that won't always be the case. 12
13
When Perl sees a value without quotes around the value, Perl assumes 14
initially that this is a function call. If there actually is a function called red, 15
the function would be called and the return value of the function would be 16
assigned to the $var variable: 17
Only if red isn't a function would it be considered a scalar value. As a 25
result, it is always safer to place quotes around the value: 26
27
$var="red"; 28
2 – Scalar Variables ©2018 One Course Source, Inc. Page 48 2.5 Strings vs. Numbers
1 2
While numbers and strings are both scalar data to Perl, they are 3
sometimes treated differently (dependent on how they are used). 4
5
When numbers are used in a "string context", they are converted into 6
strings first and then "used". String context includes: 7
8
➢ String operators ("." or "x") 9
➢ String functions (see previous page) 10
➢ The assignment operation (the = sign) 11
➢ String comparison (described in a later unit) 12
➢ Regular expressions (described in a later unit) 13
14
The method Perl uses to convert numbers to strings is very simple. 15
Essentially, the number is treated as if there were quotes around it. The 16
only time the number is modified is when it contains unnecessary "0"'s 17
after the decimal point. They are dropped when the number is used as a 18
DB<1> print "abc".12345 23
abc12345
24
DB<2> print "abc".123.45 25
abc123.45
26
DB<3> print "abc".123.4500 27
abc123.45
2 – Scalar Variables ©2018 One Course Source, Inc. Page 49 String to number conversion is a bit more complex. Perl will "look" at the 1
first character of the string and…:
2 3
➢ …if it is a number (0-9) or a decimal point then Perl will continue
4
to look for more numbers. Once it finds a character that is not 5
either a number or decimal point, it will stop looking and will 6
convert the string into what it has found to that point. 7
8
➢ …if it is white space (new line, space, tab, etc.), Perl will ignore it
9
and look at the next character to determine if it is a number, 10
decimal point or non-number. 11
12
➢ …if it isn't a number, a decimal point or white space, then the
13
string is treated as the value zero (0). 14
15
Examples: 16
17
DB<1> print "123abc"+10 18
DB<3> print "abc123" +10 22
Perl is also smart enough to know that a number can’t have two decimal
27
points. Once a second decimal point is discovered, Perl stops looking and 28
treats all characters to that point as the number: 29
30
DB<1> print "9.999.999" + 10 31
19.999
2 – Scalar Variables ©2018 One Course Source, Inc. Page 50 The assignment operation
1 2
It is important to remember that the assignment operation is a string 3
operation. This may sometimes pose problems: 4
5
DB<1> $num=120.4500000 6
In the previous example, we tried to assign a very precise number to the 10
variable $num. However, because the assignment operation is a string 11
operation, the "unnecessary" zeros were removed from the number. In 12
most cases this isn't a problem, but if you want to show how precise the 13
number really is, this is a disadvantage. 14
15
To avoid this, use quotes around the number: 16
17
DB<1> $num="120.4500000" 18
Note that this does not make $num into a variable that holds a string. It is 22
a scalar variable, not a numeric or string variable. If you use a numeric 23
operator or function on the variable, then it will be treated as a number; use 24
a string operator or function on the variable, then it will be treated as a 25
string. 26
2 – Scalar Variables ©2018 One Course Source, Inc. Page 51
Try it!
1 2
Execute the following command to enter the Perl debugger: 3
4
perl –d –e “1;”
5 6
Execute the following commands in the Perl debugger to test the difference 7
between strings and numbers: 8
9
print “1000 monkeys” + 5;
10
print length(123.45000);
11
print “work” / “time”;
12 13
Did you get the results that you expected? If not, review the last section 14
and determine why the output was different than you expected. 15
16
Exit the Perl debugger by executing the following debugger command: 17
18
quit
2 – Scalar Variables ©2018 One Course Source, Inc. Page 52 2.6 Single vs. Double Quotes
1 2
Quotes are important when dealing with strings because they tell Perl how 3
to handle the strings. 4
5
Double Quotes 6
7
There are many "special characters" that you can have within double 8
quotes. These characters are called "escape characters" because the 9
escape key (\) is used to create them: 10
11
Escape character Meaning
\t Tab
\n New line character
\r Return
\u Makes the next character upper case \l Makes the next character lower case \U Makes all following characters upper case \L Makes all following characters lower case \E Ends the \U and \L modifications
\f Form feed
\b Backspace
\a Bell
2 – Scalar Variables ©2018 One Course Source, Inc. Page 53 Examples:
1 2
DB<1> print "It is a good idea to learn Perl\n" 3
It is a good idea to learn Perl
4 5
DB<2> print "hello\t\t\tgoodbye" 6
hello goodbye
7
DB<3> print "hello\b\b\b\b\bgoodbye" 8
goodbye
9
DB<4> print "The \Usign\E said \Ustop\E\n" 10
The SIGN said STOP
11 12
Within double quotes the "$" and "@" characters are also special 13
characters. The "$" character is used to specify a scalar variable while the 14
"@" character is used to specify an array variable. Variable dereferencing 15
(returning the value that is assigned to the variable) takes place within 16
double quotes: 17
18
DB<1> $code="A127Z" #sets a scalar variable 19
DB<2> print "The code is $code" 20
The code is A127Z
21 22
If you want to print double quotes within a double quoted string, you need 23
to put an escape character (backslash) preceding the double quotes: 24
25
DB<1> print "The key word is \"test\"" 26
The key word is "test"
2 – Scalar Variables ©2018 One Course Source, Inc. Page 54 Single Quotes
1 2
Almost all of the characters within single quotes are treated as plain 3
characters. The only special characters within single quotes are single 4
quotes and (sometimes) escape characters: 5
6
DB<1> print 'Bob's new car is broken' 7
Substitution replacement not terminated at (eval
8
4)[C:/Perl/lib/perl5db.pl:1521] line 2. 9
DB<2> print 'The last character is \' 10
Can't find string terminator "'" anywhere before EOF at (eval
11
5)[C:/Perl/lib/perl5db.pl:1521] line 2.
12 13
In order to have a single quote within a single quoted string, you must put 14
an escape character before it: 15
16
DB<1> print 'Bob\'s new car is broken' 17
Bob's new car is broken
18 19
Since an escape character before a single quote makes it into a plain 20
character, you need to escape the escape character in such cases: 21
22
DB<1> print 'The last character is \\' 23
The last character is \
24 25
Within single quotes the escape character has no special meaning in front 26
of other characters and the $ character is just a plain character: 27
DB<2> print 'The total is $total' 31
The total is $total
2 – Scalar Variables ©2018 One Course Source, Inc. Page 55
Try it!
1 2
Execute the following command to enter the Perl debugger: 3
4
perl –d –e “1;”
5 6
Execute the following commands in the Perl debugger to practice how 7
single and double quotes are different: 8
9
print “Hello there\tBob; how are\nyou today?”;
10
print ‘Hello there\tBob; how are\nyou today?’;
11 12
Exit the Perl debugger by executing the following debugger command: 13
14
quit
2 – Scalar Variables ©2018 One Course Source, Inc. Page 56 2.7 Scalar Variables
1 2
A "scalar value" is a single item of data. This data can consist of 3
characters that are found in the ASCII text table. Scalar variables are used 4
to store scalar values. The "$" character is used to specify a variable 5
name: 6
7
$var=value; 8
9
The variable name ($var in the example above) can contain alpha 10
characters (lower and upper case), numbers and underscore characters. It 11
must also start with an alpha character or an underscore character. While 12
some Perl built-in variables can start with a numeric character, the 13
variables that you create cannot start with a numeric character. 14
15
To dereference the value a variable contains, specify the variable's name: 16
17
DB<1> $test=94 18
DB<2> print "The result of the test is $test" 19
The result of the test is 94
2 – Scalar Variables ©2018 One Course Source, Inc. Page 57 2.8 Undefined variables
1 2
If you attempt to reference a variable that has not been defined, Perl does 3
not consider this an error. The value that Perl returns depends upon how 4
the variable is being used. In numeric operations, Perl will return 0; in 5
string operations, Perl will return "" (null string): 6
7
DB<1> print "The name of the car is $name" 8
The name of the car is
9
DB<2> print "The value is: " , $total + 8 10
The value is: 8
11 12
Note: The comma used in the second example separates the string from 13
the mathematical operation. This sequence of items separated by 14
commas is called a list in Perl. 15
2 – Scalar Variables ©2018 One Course Source, Inc. Page 58 In some cases, you don't want to perform an operation if a variable isn't 1
defined. The defined function can be used to check if a variable is defined 2
or not. If the variable is defined, defined returns a "true" value; if the 3
variable isn't defined, defined returns a "false" value". 4
5
These values can be used in conditional statements. In a later unit we will 6
discuss conditional statements in detail. The following code is just a brief 7
print 'The variable $total is not defined', "\n"; 18
example, the first print statement is executed if $total is defined. 24
The second print statement is executed if $total is not defined. 25
26
➢ The curly braces { } define a "block" of statements. Blocks are 27
required for conditional statements to tell Perl what statements to 28
execute if the condition is true (or false in the case of the else 29
portion). 30
2 – Scalar Variables ©2018 One Course Source, Inc. Page 59 To "undefine" a variable that has been defined, use the undef function: 1
2
DB<1> $total=95 3
DB<2> print "The total is $total\n" 4
➢ The outcome of the if statement will be to print "no" since $total is not 16
defined. 17
18
➢ Setting a variable to "" or 0 does not "undefine" it. 19
20
➢ In the Perl debugger the statement is automatically executed after 21
you press the "Enter" key. To continue the command, type a 22
backslash character right before the "Enter" key. This is the purpose 23
of the backslash characters that are use with the if statement in the 24
previous example. 25
2 – Scalar Variables ©2018 One Course Source, Inc. Page 60
Try it!
1 2
Execute the following command to enter the Perl debugger: 3
4
perl –d –e “1;”
5 6
Execute the following commands in the Perl debugger to practice setting 7
and unsetting variables: 8
9
if (defined $person) {print “yes”};
10
$person=”Nick”;
11
if (defined $person) {print “yes”};
12
undef $person;
13
if (defined $person) {print “yes”};
14 15
Exit the Perl debugger by executing the following debugger command: 16
17
quit
2 – Scalar Variables ©2018 One Course Source, Inc. Page 61 2.9 Auto increment and Auto decrement
1 2
As mentioned previously, the "++" and "--" operators can be used to alter 3
numeric variables. The ++ (Auto increment) operator will add 1 to the 4
variable. The "--" (Auto decrement) operator will subtract 1 from the 5
The difference between $i++ and ++$i is when the incrementing takes 18
2 – Scalar Variables ©2018 One Course Source, Inc. Page 62 If the operator occurs after the variable, then the original value is first
1
returned (and, in this case, assigned to the $b variable) and then the 2
variable is incremented: 3
WARNING: Don’t use auto increment or auto decrement on variables that
12
contain strings. As mentioned in previously, Perl will (normally) try to 13
convert the string into a number. Often this results in a "logical error": 14
15
DB<1> $name="Bob Smith" 16
In this example, Perl treats "Bob Smith" as the number 0, then adds 1 to 0 21
and reassigns $name to the value of 1. 22
2 – Scalar Variables ©2018 One Course Source, Inc. Page 63 Perl Magic with the auto-increment operator
1 2
The Perl documentation on the auto-increment operator includes the 3
following statement: 4
5
"The auto-increment operator has a little extra built-in magic to it. If you 6
increment a variable that is numeric, or that has ever been used in a 7
numeric context, you get a normal increment. If, however, the variable has 8
been used in only string contexts since it was set, and has a value that is 9
not the empty string and matches the pattern /^[a-zA-Z]*[0-9]*\z/ , the 10
increment is done as a string, preserving each character within its range, 11
with carry" 12
13
This fancy description is meant to describe the following behavior: 14
15
DB<1> $name="Bob" 16
A simpler way of describing this behavior is that if the variable contains 21
only alphanumeric characters (and not just numeric characters), then the 22
auto-increment operator will increase the value of the "string" by one 23
(based on the ASCII text table). 24
25
Note: The point behind this isn't to encourage you to use this feature, but 26
rather to make you aware of this "Perl magic" in the event you come across 27
some code that makes use of this feature. 28
2 – Scalar Variables ©2018 One Course Source, Inc. Page 64 To increment or decrement a variable by a different value than 1, use this 1
This method also allows the use of multiplication and division: 12
Cool trick: You can append a string to an existing string variable by 22using the following: 23
24
$var .= “string”; 25
2 – Scalar Variables ©2018 One Course Source, Inc. Page 65
Try it!
1 2
Execute the following command to enter the Perl debugger: 3
4
perl –d –e “1;”
5 6
Execute the following commands in the Perl debugger to practice variable 7
modification with the operators that were covered in this section: 8
9
$total=1000;
10
$total++;
11
print $total;
12
$result=++$total;
13
print “$total and $result”;
14
$total *=3;
15
print $total;
16 17
Exit the Perl debugger by executing the following debugger command: 18
19
quit
2 – Scalar Variables ©2018 One Course Source, Inc. Page 66 2.10 Reading data from the user
1 2
There are several methods of reading input: 3
4
➢ The standard input filehandle 5
6
➢ The diamond operator (discussed in a later unit) 7
8
➢ User created filehandles (discussed in a later unit) 9
10
The most common method of reading input is the standard input filehandle. 11
A filehandle is a connection between your script and a "port". The standard 12
input filehandle reads data from the port connected to standard input 13
(usually data coming from the keyboard, but this data could also come 14
from a file or the output of another process). 15
16
<STDIN> represents the standard input filehandle. In the following 17
example, the user should be prompted to provide their age via the 18
keyboard. Whatever the user types is placed in the $age variable: 19
20
print "Please enter your age:"; 21
$age=<STDIN>; 22
2 – Scalar Variables ©2018 One Course Source, Inc. Page 67 2.11 chomp & chop
1 2
When data is read from <STDIN>, the data that is stored in the variable 3
includes all the characters that are typed by the user. For example, 4
consider if a user were asked for his/her age and the user provides the 5
data displayed in bold below: 6
7
DB<1> print "Please enter your age: "; $age=<STDIN> 8
Please enter your age: 35 9
10
So, in this example, $age will store the string "35\n". Why "\n"? Because 11
the user had to press the Enter (or Return) key after typing "35". The Enter 12
key, "\n", is also stored in the variable. Since this extra character often 13
causes problems, it is useful to know how to get rid of it. 14
15
To verify that there actually is a newline character in the variable, consider 16
the following output: 17
18
DB<1> print "Please enter your age: "; $age=<STDIN> 19
Please enter your age: 35 20
DB<2> print length($age) 21
3
22
DB<3> print "You are $age years old" 23
There are two Perl statements you can use to eliminate extra character 27
from the end of a string: chop and chomp. 28
2 – Scalar Variables ©2018 One Course Source, Inc. Page 68 The chop statement
1 2
The chop statement will remove (and return) the last character of a string: 3
4
$var="Now is a good time to buy stock\n"; 5
chop $var; #chops off new line character 6
print chop $var; #chops off "k" and returns 7
#value to print statement 8
$char=chop $var; #chops off "c" and returns 9
#value to assignment 10
11
The chomp statement 12
13
The chomp statement will only remove new line characters at the end of a 14
string: 15
16
$var="Now is a good time to buy stock\n"; 17
When you know that you only want to remove a newline character, it is 21
safer to use the chomp statement. When you want to remove any 22
character, then the chop statement is better. 23
24
Cool trick: You can receive input and use the chomp statement at the 25same time using the following syntax: 26
27
chomp($name=<STDIN>); 28
2 – Scalar Variables ©2018 One Course Source, Inc. Page 69
Try it!
1 2
Execute the following command to enter the Perl debugger: 3
4
perl –d –e “1;”
5 6
Execute the following commands in the Perl debugger to practice dealing 7
with user input: 8
9
$person=<STDIN>;
10
print $person . “ ” . print length($person);
11
chomp $person;
12
print $person . “ ” . print length($person);
13
chomp $person;
14
print $person . “ ” . print length($person);
15
chomp $person;
16
print $person . “ ” . print length($person);
17 18
Exit the Perl debugger by executing the following debugger command: 19
20
quit
2 – Scalar Variables ©2018 One Course Source, Inc. Page 70 2.12 Curly braces
1 2
Consider the following code: 3
4
DB<1> $name="Bob" 5
DB<2> print "$name would rather be called $nameby" 6
Bob would rather be called
7 8
The intended output of this script is: 9
10
Bob would rather be called Bobby 11
12
Unfortunately, this script will result in a logical error. Perl will return the 13
value of the $nameby variable (when what is really wanted is the value of 14
the $name variable and "by" to be treated as plain text). Because this 15
variable doesn’t exist, Perl returns a null string.
16 17
To avoid this, place curly braces around the variable name: 18
19
DB<1> $name="Bob"
20
DB<2> print "$name would rather be called ${name}by"
21
Bob would rather be called Bobby
22 23
The curly braces tells Perl that the variable name is $name and that the 24
2 – Scalar Variables ©2018 One Course Source, Inc. Page 71 2.13 Additional Resources
In each unit, resources are provided to provide the learner with a source for more information. These resources may include online documentation, local (on your system) documentation and traditional books.
Due to the fact that these resources changes (especially online resources), we provide these resources on our web site instead of printing them in our courseware. This allows us to provide updated resources in a timely
manner.
For this unit, the resources can be found here:
2 – Scalar Variables ©2018 One Course Source, Inc. Page 72 2.14 Lab Exercises
Important note: If you did not finish the previous lab, either finish it before starting this lab or use the completed cb1.pl provided in the lab answers folder.
Edit the file called cb1.pl and perform the following enhancements (save the changes into a file called cb2.pl):
➢ Have the user's name read into a variable called $name
➢ Have the user's current balance printed (Note: HARD CODE the current balance to be "100" for now) followed by this menu:
1. Enter a deposit 2. Enter a withdrawal 3. Enter a check
4. Lookup a check by # 5. Lookup a check by date 6. Print a statement
7. Exit program
Please enter your menu option:
➢ Have your script prompt the user for their menu choice and assign the input to a variable called $choice (don't forget to chomp off the new line character).
When you have completed your work, compare your script against the cb2.pl file provided in lab answers. During the instructor-led classes, the instructor may review the answer script and provide you with the
3 – Array Variables ©2018 One Course Source, Inc. Page 73 Unit Three
Array Variables
Unit topics: Page
3.1 ... Array Variables 74 3.2 ... Referencing Array Elements 75 3.3 ... Adding & removing elements in an array 79 3.4 ... The splice function 82 3.5 ... Using for loops 85 3.6 ... Using foreach loops 87 3.7 ... The reverse statement 91 3.8 ... The sort operator 92 3.9 ... The qw and qq statements 95 3.10 ... Arrays used in scalar context 96 3.11 ... Additional Resources 97 3.12 ...Lab Exercises 98
3 – Array Variables ©2018 One Course Source, Inc. Page 74 3.1 Array Variables
1 2
Array variables are used to store lists (groups) of scalar data. The 3
following describes important information about array variables: 4
5
➢ The variable starts with a "@" symbol (not a $ symbol like scalar 6
variables). 7
8
➢ The variable name rules (start with a alpha char or underscore 9
character, use only alphanumeric & underscore chars) for scalar 10
variables also apply to array variable names. 11
12
➢ Array sizes don't have to be declared; Perl dynamically takes care of 13
the size of the array. 14
15
➢ Individual scalar data within the array are referred to as "elements". 16
17
➢ An element can be treated as either a string or number. 18
19
To create an array, use the following syntax: 20
21
@colors=("red", "blue", "green"); 22
23
Note: the value on the right-hand side of the = operator is called a list. A 24
list is generated by placing a series of scalar values, separated by 25
commas, within a set of parenthesis. This list is the data structure that an 26
array holds. 27
3 – Array Variables ©2018 One Course Source, Inc. Page 75 3.2 Referencing Array Elements
1 2
To reference an element in an array, use the following syntax: 3
4
print "$colors[0] is the color name in the list\n"; 5
6
Array elements are indexed by integers (starting from 0). Therefore, the 7
first element is element "0", the second element is element "1", and so 8
forth. 9
10
The most confusing aspect of referring to an element is the use of the "$" 11
character. Why "$" and not "@"? 12
13
Think of it this way: "@" is used to indicate array data and "$" is used to 14
indicate scalar data. An element of an array is scalar data (a single value), 15
therefore, when referring to it, use a "$" character. 16
17
If you wanted to print the entire array (or a portion of it), you would use the 18
"@" symbol: 19
20
print "@colors"; 21
22
Note: Without the quotes (""), all of the elements would be printed "Mashed 23
together". 24
3 – Array Variables ©2018 One Course Source, Inc. Page 76 Some other referencing examples
1 2
print "$colors[1] \n"; #prints the second element in the array. 3
4
print "@colors[1..3]\n"; #prints from the second to the fourth element 5
in the #array. 6
7
print "@colors[1,3]\n"; #prints from the second and the fourth 8
element in #the array. 9
10
print "$colors[$#colors] \n"; #prints the last element in the array ($#arr 11
holds the #last index number of the array 12
"arr"). 13
14
print "$colors[-1]\n"; #prints the last element in the array 15
(alternative method). 16
17
print "$colors[99]\n"; #prints the 100th element in the array. If not
18
#defined, prints "" (0 in numeric situations) 19