Home > Articles > Web Development

Scalars, Arrays, and Hashes in Perl

In this chapter from Perl by Example, 5th Edition, Ellie Quigley covers scalars in more depth, as well as arrays and hashes.
This chapter is from the book

This chapter is from the book

05fig00.jpg

5.1 More About Data Types

By the end of this chapter, you will be able to read the following Perl code:

use strict;
use warnings;
my @l = qw/a b c d d a e b a b d e f/;
my %hash=();

foreach my $key (@l){
   $hash{$key} = $key;
}
print join(" ",sort keys %hash),"\n";

Again, please take note that each line of code, in most of the examples throughout this book, is numbered. The output and explanations are also numbered to match the numbers in the code. When copying examples into your text editor, don’t include these numbers, or you will generate errors.

5.1.1 Basic Data Types (Scalar, Array, Hash)

In Chapter 3, “Perl Scripts,” we briefly discussed scalars. In this chapter, we will cover scalars in more depth, as well as arrays and hashes. It should be noted that Perl does not provide the traditional data types, such as int, float, double, char, and so on. It bundles all these types into one type, the scalar. A scalar can represent an integer, float, string, and so on, and can also be used to create aggregate or composite types, such as arrays and hashes.

Unlike C or Java, Perl variables don’t have to be declared before being used, and you do not have to specify what kind data will be stored there. Variables spring to life just by the mere mention of them. You can assign strings, numbers, or a combination of these to Perl variables and Perl will figure out what the type is. You may store a number or a list of numbers in a variable and then later change your mind and store a string there. Perl doesn’t care.

A scalar variable contains a single value (for example, one string or one number), an array variable contains an ordered list of values indexed by a positive number, and a hash contains an unordered set of key/value pairs indexed by a string (the key) that is associated with a corresponding value (see Figure 5.1). (See Section 5.2, “Scalars, Arrays, and Hashes.”)

Figure 5.1

Figure 5.1 Namespaces for scalars, arrays, and hashes in package main.

5.1.2 Package, Scope, Privacy, and Strictness

Package and Scope.

The Perl sample programs you have seen in the previous chapters are compiled internally into what is called a package, which provides a namespace for variables.

An analogy often used to describe a package is the naming of a person. In the Johnson family, there is a boy named James. James is known to his family and does not have to qualify his name with a last name every time he is being called to dinner. “James, sit down at the table” is enough. However, in the school he attends there are several boys named James. The correct James is identified by his last name, for example, “James Johnson, go to the principal’s office.”

In a Perl program, “James” represents a variable and his family name, “Johnson,” a package. The default package is called main. If you create a variable, $name, for example, $name belongs to the main package and could be identified as $main::name, but qualifying the variable at this point is unnecessary as long as we are working in a single file and using the default package, main. Later when working with modules, we will step outside of the package main. This would be like James going to school. Then we could have a conflict if two variables from different packages had the same name and would have to qualify which package they belong to. For now, we will stay in the main package. When you see the word main in a warning or error message, just be aware that it is a reference to something going on in your main package.

The scope of a variable determines where it is visible in the program. In the Perl scripts you have seen so far, the variables live in the package main and are visible to the entire script file (that is, global in scope). Global variables, also called package variables, can be changed anywhere within the current package (and other packages), and the change will permanently affect the variable. To keep variables totally hidden within their file, block, or subroutine programs, we can define lexical variables. One way Perl does this is with the my operator. An entire file can be thought of as a block, but we normally think of a block as a set of statements enclosed within curly braces. If a variable is declared as a my variable within a block, it is visible (that is, accessible within that block and any nested blocks). It is not visible outside the block. If a variable is declared with my at the file level, then the variable is visible throughout the file. See Example 5.1.

Example 5.1

   # We are in package main
1  no warnings;   # warnings turned off so that output is
                  # not clouded with warning messages

2  my $family="Johnson";  # file scope
3  {  my $mother="Mama";  # block scope
      my $father="Papa";
      my ($cousin, $sister, $brother);
4     my $family="McDonald";   # new variable
5     print "The $family family is visible here.\n";
   }
6  print "$mother and $father are not visible here.\n";
7  print "The $family family is back.\n";

(Output)
5  The McDonald family is visible here.
6     and are not visible here.
7  The Johnson family is back.

Explanation

  • 1. warnings are turned off so that you can see what’s going on without being interrupted with warning messages. If warnings had been turned on, you would have seen the following:

    Name "main::father" used only once: possible typo at my.plx line 10.
    Name "main::mother" used only once: possible typo at my.plx line 10.
    The McDonald family is visible here.
    Use of uninitialized value $mother in concatenation (.) or string at
              my.plx line 10.
    Use of uninitialized value $father in concatenation (.) or string at
              my.plx line 10.
    And are not visible here.
    The Johnson family is back.

    The messages are telling you that for package main, the $mother and $father variables were used only once. That is because they are not visible outside of the block where they were defined, and by being mentioned outside the block, they are new uninitialized variables.

  • 2. The $family variable is declared as a lexical my variable at the beginning of the program. The file is considered a block for this variable giving it file scope; that is, visible for the entire file, even within blocks. If changed within a block, it will be changed for the rest of the file.
  • 3. We enter a block. The my variables within this block are private to this block, visible here and in any nested blocks, and will go out of scope (become invisible) when the block exits.
  • 4. This is a brand new lexical $family variable (McDonald). It has nothing to do with the one created on line 2. The first one (Johnson) will be visible again after we exit this block.
  • 6. The my variables defined within the block are not visible here; that is, they have gone out of scope. These are brand new variables, created on the fly, and have no value.
  • 7. The Johnson family is back. It is visible in the outer scope.

The purpose in mentioning packages and scope now is to let you know that the default scope of variables in the default main package, your script, is global; that is, accessible throughout the script. To help avoid the future problems caused by global variables, it is a good habit (and often a required practice) to keep variables private by using the my operator. This is where the strict pragma comes in.

The strict pragma (a pragma is a compiler directive) is a special Perl module that directs the compiler to abort the program if certain conditions are not met. It targets barewords, symbolic references, and global variables. For small practice scripts within a single file, using strict isn’t necessary, but it is a good, and often required, practice to use it (a topic you can expect to come up in a Perl job interview!).

In the following examples, we will use strict primarily to target global variables, causing your program to abort if you don’t use the my operator when declaring them.

Example 5.2

1  use strict;
2  use warnings;
3  $family="Johnson";  # Whoops! global scope
4  $mother="Mama";
5  $father="Papa";
6  print "$mother and $father are here.\n"; # global
7  print "The $family family is here.\n";

(Output)
Global symbol "$family" requires explicit package name at strictex.plx
line 3.
Global symbol "$mother" requires explicit package name at strictex.plx
line 4.
Global symbol "$father" requires explicit package name at strictex.plx
line 5.

Global symbol "$mother" requires explicit package name at strictex.plx
line 6.
Global symbol "$father" requires explicit package name at strictex.plx
line 6.
Global symbol "$family" requires explicit package name at strictex.plx
line 7.
Execution of strictex.plx aborted due to compilation errors.

Explanation

  • 1. The strict pragma is being used to restrict all “unsafe constructs.” To see all the restrictions, type the following at your command-line:

    perldoc strict

    If you just want to target global variables, you would use strict with an argument in your program, such as:

    use strict 'vars'
  • 2. The warnings pragma is turned on, but will not issue warnings because strict will supersede it, causing the program to abort first.
  • 3. This is a global variable in the program, but it sets off a plethora of complaints from strict everywhere it is used. By preceding $family and the variables $mother and $father with the my operator, all will go well. (You can also explicitly name the package and the variable, as $main::family to satisfy strict. But then, the warnings pragma will start complaining about other things, as discussed in the previous example.)
  • 6, 7. Global variables again! strict complains, and the program is aborted.

The warnings and strict pragmas together are used to help you find typos, spelling errors, and global variables. Although using warnings will not cause your program to die, with strict turned on, it will, if you disobey its restrictions. With the small examples in this book, the warnings are always turned on, but we will not turn on strict until later.

5.1.3 Naming Conventions

Variables are identified by the “funny characters” that precede them. Scalar variables are preceded by a $ sign, array variables are preceded by an @ sign, and hash variables are preceded by a % sign. Since the “funny characters” (properly called sigils) indicate what type of variable you are using, you can use the same name for a scalar, array, or hash (or a function, filehandle, and so on) and not worry about a naming conflict. For example, $name, @name, and %name are all different variables; the first is a scalar, the second is an array, and the last is a hash.1

Since reserved words and filehandles are not preceded by a special character, variable names will not conflict with them. Names are case sensitive. The variables named $Num, $num, and $NUM are all different. If a variable starts with a letter, it may consist of any number of letters (an underscore counts as a letter) and/or digits. If the variable does not start with a letter, it must consist of only one character. Perl has a set of special variables (for example, $_, $^, $., $1, $2) that fall into this category. (See Section A.2, “Special Variables,” in Appendix A.) In special cases, variables may also be preceded with a single quote, but only when packages are used. An uninitialized variable will get a value of zero or undef, depending on whether its context is numeric or string.

5.1.4 Assignment Statements

The assignment operator, the equal sign (=), is used to assign the value on its right-hand side to a variable on its left-hand side. Any value that can be “assigned to” represents a named region of storage and is called an lvalue.2 Perl reports an error if the operand on the left-hand side of the assignment operator does not represent an lvalue.

When assigning a value or values to a variable, if the variable on the left-hand side of the equal sign is a scalar, Perl evaluates the expression on the right-hand side in a scalar context. If the variable on the left of the equal sign is an array, then Perl evaluates the expression on the right in an array or list context (see Section 5.2, “Scalars, Arrays, and Hashes”).

Example 5.3

(The Script)
   use warnings;
   # Scalar, array, and hash assignment
1  my $salary=50000;                   # Scalar assignment
2  my @months=('Mar', 'Apr', 'May');   # Array assignment
3  my %states= (                       # Hash assignment
      CA => 'California',
      ME => 'Maine',
      MT => 'Montana',
      NM => 'New Mexico',
   );
4  print "$salary\n";
5  print "@months\n";
6  print "$months[0], $months[1], $months[2]\n";
7  print "$states{'CA'}, $states{'NM'}\n";
8  print $x + 3, "\n";             # $x just came to life!
9  print "***$name***\n";          # $name is born!


(Output)
4  50000
5  Mar Apr May
6  Mar, Apr, May
7  California, New Mexico
8  3
9  ******

Explanation

  • 1. The scalar variable $salary is assigned the numeric literal 50000.*
  • 2. The array @months is assigned the comma-separated list, ‘Mar ‘, ‘ Apr ‘, May ‘. The list is enclosed in parentheses and each list item is quoted.
  • 3. The hash, %states, is assigned a list consisting of a set of strings separated by either a digraph symbol (=>) or a comma. The string on the left is called the key and it is not required that you quote the key, unless it starts with a number. The string to the right is called the value. The key is associated with its value.
  • 5. The @months array is printed. The double quotes preserve spaces between each element.
  • 6. The individual elements of the array, @months, are scalars and are thus preceded by a dollar sign ($). The array index starts at zero.
  • 7. The key elements of the hash, %states, are enclosed in curly braces ({}). The associated value is printed. Each value is a single value, a scalar. The value is preceded by a dollar sign ($).
  • 8. The scalar variable, $x, is referenced for the first time with an initial value of undef. Because the number 3 is added to $x, the context is numeric. $x then gets an initial value of 0 in order to perform arithmetic. Initially $x is null.
  • 9. The scalar variable, $name, is referenced for the first time with an undefined value. The context is string.

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.

Overview


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.

Surveys

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.

Newsletters

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.

Security


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

Children


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

Marketing


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.

Choice/Opt-out


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.

Links


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