Scalars, Arrays, and Hashes in Perl
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 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.