Home > Articles > Web Development > Perl

Introducing Perl

Get acquainted with this versatile high-level language through examining variables, control flow constructs, regular expressions, and functions.
This chapter is from the book

This chapter is from the book

The goal in this chapter is to demonstrate many fundamental Perl features so that you may start writing Perl programs quickly. Subsequent chapters will drill more deeply into each of the topics presented here.

1.1 Getting Started

Programming languages come in all shapes and sizes. There are many ways of categorizing them. Some are considered high-level and some are considered low-level. The basic difference between these characterizations is the amount of code you need to write to express an idea. The less code you need to write, the higher the level of the language. Perl is a high-level programming language. Sometimes it is compiled and sometimes it is interpreted.

Perl was written in the early 1980s by a modern-day Renaissance man named Larry Wall. Perl combines the best features of the Unix shells, C language, and some of the more famous Unix utilities such as awk, grep, and sed. Once you are familiar with Perl, you will probably choose Perl over any of the shells, if management gives you a choice.

Perl is often referred to as a scripting language. Likewise, Perl programs are often called Perl scripts, but this distinction is largely irrelevant. Perl is currently used in a wide variety of domains, including system administration, client/server and CGI applications, text and file processing, database retrievals, biomedical processing, and many other domains.

Perl is extremely easy to learn even though there are some notational learning curves to be conquered in certain advanced features of the language.

You can download Perl freeware at the site www.activestate.com. This site has versions of Perl for most major platforms, including Windows variants, Unix variants, and Microsoft.net. For the Macintosh, you can visit www.macperl.com. For any and all information about Perl, visit www.perl.com.

Similar to other pieces of software, Perl has undergone quite a transformation since the first version was released in January 1988. Perl 2.0 was released in June 1988 and Perl 3.0 was released in October 1989. However, the most important releases are the Perl 4 release in March 1991 and the Perl 5 release in October 1994. A new version of Perl, Perl 5.6, was released in early 2001.

We will assume that you have installed Perl on your machine and that you are ready to write Perl programs.

1.1.1 The first Perl program

Here's a simple Perl program:

#     first.pl
print "Please enter your name ";
$name = <STDIN>;
chomp ($name);
print "Your name is $name";

Perl programs are written using your favorite text editor. Once you have typed your code into a file, there is no need to compile it—you simply execute it.

The # is a special character in Perl. Anything that follows this character is interpreted as a comment. A comment is terminated by the end of a line. Thus, the first four lines above are comments. (Actually, the top line is treated in a special way on Unix systems—we will see this later.)

Note that all Perl statements end in a semicolon. The print statement places data on the standard output file, the display. In this case, a prompt is displayed requesting that the user enter a name. Let's assume for now that the data that is printed needs to be wrapped in double quotes.

The next line reads a line typed by the user on the keyboard. The data will be stored inside the Perl variable $name. This data includes the newline character. In Perl, all variable names have some punctuation associated with them. The $ signifies that this variable can hold one value. This one value could be a number, a string, or something else. In any case, it will be treated as a single value. In this case, the string typed in by the user is held there. Variables that begin with $ are referred to as scalar variables. We will have more to say about these variables later.

<STDIN> is the Perl operator for reading a line from the standard input file, the keyboard. A line is defined as all of the characters up to and including the newline character. This character is generated when you press the Return (or Enter) key. Thus, the following code reads a line from the user at the keyboard:

$name = <STDIN>;

chomp is a Perl function that discards the last character in a variable only if it is a newline. Thus, the newline is discarded from $name. Finally, another print is used to print the value of the variable $name. Incidentally, there is another function, named chop, which unconditionally eliminates the last character of a variable.

Before we show how first.pl is executed, we need to make a slight diversion and mention a few differences between running your Perl scripts on a Unix system vs. running scripts on a Windows system. On Unix, the first line of every Perl script must appear as:


Unix shell programmers may recognize this. The first two characters are interpreted as special by any of the Unix shells. These two characters, #!, tell the Unix shell to use the command /usr/bin/perl to execute this script. So if you are on a Unix system, change the first line of your scripts to the complete pathname of the Perl executable, which in our case is #!/usr/bin/perl.

On Unix, after you have prepared your script, it should be made executable using the chmod command. We'll use the % as the system prompt for all of our examples:

% chmod 755 first.pl

Now you can simply execute the program as follows:

% first.pl

On a Windows machine, the easiest way to proceed is to open a DOS window and type the following to execute first.pl. On Windows, the #! line is treated as a comment.

% perl first.pl
Please enter your name Michael
Your name is Michael

Here's an example of how to execute this program on Unix:

% first.pl
Please enter your name Michael
Your name is Michael

Note that throughout the book, what the user types will be in bold letters. You can also see that all non-comment lines end with the semicolon character. Syntactically, the semi-colon is a statement separator, not a statement terminator; thus, the last statement in a script, or the last statement of any block (statements delimited by curly braces ({})), does not have to be terminated with a semicolon. However, it is good practice to place one there since you may later add some Perl code to the end of the script.

1.1.2 Some elementary I/O

Thus far, we have seen the print function used several times. We now would like to explore how a Perl program performs elementary input and output. Whenever you wish to place some information on the user's display, you use the print function. By default, your data will be sent to the standard output file, the display. Perl programs understand the concept of a filehandle, a name that is associated with a file. Perl defines a few builtin filehandles, one of which is STDOUT. If you wish, you may use a filehandle in the print function to explicitly specify the destination for the data to be printed. The following two lines are therefore functionally identical to one another:

print STDOUT "this string gets sent to the display";
print "this string gets sent to the display";

You may also create your own filehandle by using the open function. This function associates a filehandle with an actual disk file. open contains two arguments, the first of which is a filehandle and the second of which contains the name of the file to be created and the mode (input or output) of the file. The access mode is given as a punctuation symbol. The following open function associates the file named mydata with the filehandle OUTPUT. The > punctuation symbol specifies that the file will be used as an output file. Be careful here. If the file already exists, its data will be truncated.

The name OUTPUT is one of our choosing. We could have called it OUT or anything else. When you create a filehandle, use a naming convention that is mnemonically sound.

Here's a sample program, iodemo.pl, that creates a file and sends some data to the file associated with the filehandle and to the display:

#    iodemo.pl
open(OUTPUT,"> mydata");
print STDOUT "Welcome to the Perl language\n";
print OUTPUT "This data goes to a file\n";
print STDOUT "I think you will enjoy it\n";
print OUTPUT "Likewise this goes to a file also\n";

When you execute the above program, you'll only see two lines on the display. The other two lines have been sent to the file named mydata. Note that we've also placed the newline character, \n, at the end of each line. Without this character, both strings end up on the same physical output line. This is a good place to do some testing of your own. If you load a copy of iotest.pl, you may remove the newline characters, run the program again, and observe the results.

Notice that this program created a file named mydata. If you want to see the two lines in that file, you may use whichever utility comes with your system to display them (e.g., cat on Unix or type with Windows).

% iodemo.pl
Welcome to the Perl language
I think you will enjoy it
% display mydata
This data goes to a file
Likewise this goes to a file also

The next example will demonstrate how to open a file for input. Ultimately, we will also need to know how to handle errors produced by open, but we will delay that until later.

You may open a file for input simply by using the < symbol at the beginning of the second argument to the open function. Of course, the file should exist or an attempt to open it will cause an error. If you do not specify any punctuation with the second argument, then the file is opened for input by default. Thus, the following lines are equivalent:

open(INPUT, "< input");
open(INPUT, "input");

Now that you have created the association between the filehandle and an actual disk file, you may use the <> operator to read from the file.

$line = <INPUT>;

$line is a scalar variable used to store the line that is entered by the user. We saw something close to this earlier when we read a line from the standard input with:

$line = <STDIN>;

The difference between the previous two lines of code is that INPUT is a filehandle created in the Perl program, whereas STDIN is a filehandle predefined in the Perl language. The snippet of code below reads the only two lines from the file mydata created above and sends them to the display:

open(INPUTFILE, "< mydata");
$firstline = <INPUTFILE>;
print "$firstline";
$firstline = <INPUTFILE>;
print "$firstline";

Each line of the form:

$variable = <SOME_FILE_HANDLE>;

reads the next line from the file associated with:


There's also a predefined filehandle, named ARGV, which is used to step through a group of files named on the command line. We will see more information about this and other filehandles later.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020