Last Updated:

Scalar arrays | PERL

An array, unlike a scalar data type that represents a single value, is a data type that is designed to store and process multiple scalar data that can be referenced by an index. All Perl arrays are one-dimensional and can be thought of as a kind of linear list of scalars. A single index is sufficient to retrieve a value stored in an array. In the program, the array is specified using a special Perl syntax construct called an array constructor. It is a list of scalar values enclosed in parentheses. List items are separated from each other by commas and represent the elements of an array:

(scalar 1, scalar 2,…, scalar n) 

As in other programming languages, the Perl array represents a set of the same type of data - scalars, but scalar data can be both numeric and string, therefore, from the point of view of other programming languages, Perl arrays store mixed data - numbers and strings. As a scalar in the array constructor, you can use a numeric or string literal or a scalar variable, whose value will be an element of the array:

(5, "multiply by", 4) # Only literals are used.
($first, 'equals', $second) # Scalar variable values are used.

An array can consist of an unlimited number of elements, or it can have none. In this case, it is called an empty array. The constructor of an empty array is a parentheses without the list () it contains.

As noted at the beginning of the paragraph, an array is characterized by the fact that any of its elements can be accessed using an index (an integer literal or a scalar variable that takes an integer value), which is specified in square brackets immediately after the array constructor. Array indexes in Perl begin with o, and negative indexes allow you to refer to elements in the reverse order:

(5, "multiply by", 4)[0] # First array element: 5.
(5, "multiply by", 4)[2] # Last element of array: 4.
(5, "multiply by", 4)[-1] f Last element of the array: 4.
(5, "multiply by", 4) [-3] # First array element: 5.

When using negative indexes, index -1 corresponds to the last element of the array, and index to n, where n is the number of elements in the array, to the first element of the array.

You cannot use an index to retrieve list items that are returned by some Perl functions. The index can be applied only to arrays or their constructors, and to do this, it is enough to enclose the list in parentheses. For example, the stat(@m) [0] construct will cause a compilation error if the return value of the stat function is a list, whereas the construct (stat (@m)) [0] will have the desired effect.

You can use the array constructor as a list item in the array constructor, but we won't get an array of arrays, that is, a multidimensional array whose elements can be accessed using multiple indexes, as a reader familiar with other programming languages would expect. The fact is that if the array constructor is used as a list element in the array constructor, then its elements are added to the elements of the array defined by the external constructor, that is, each of its elements becomes an element of the external array, increasing the number of its elements by the number of elements of the internal array. For example, an array:

(1, (2, 3), 4}

... is equivalent to an array:

(1, 2, 3, 4)

(For implementing multidimensional arrays using references, see Part 9.)

In the program, arrays are stored in special variables, the names of which begin with the "@" symbol. Declaring an array variable, or simply an array, is most often done in the assignment operator (=), on the right side of which the array constructor is usually specified:

Sarray = ($ml, '+', $m2, '=', $ml+$m2);

This example also demonstrates that you can use expressions in the array constructor, which will be discussed in the next chapter.

You can also set or get the values of the elements of an array stored in a variable by using an index. However, the indexing "operation" cannot be applied directly to the name of an array variable; it must be applied to a variable in which the first character is replaced by the symbol of the scalar variable $. Such an "inconvenience" is associated with the sequential use in Perl of the first character of a variable to indicate its type: after all, the array element is nothing more than a scalar. Examples of using an index with array variables are presented below:

$ml[0] = "First"; # Sets the first element of the @ml array.
$ml[l] = "Second"; # Sets the second element of the @ml array.
@m2 = (1, 2, 3, 4, 5); # Setting the array @t2.
print @ml, "\n", $m2[0]; # Print the toil array and
# the first element of the array @m2.

Arrays in Perl are dynamic. Adding a new element to the array automatically increases its size. You can use an index to add an element that is separated from the last defined element of the array to any number of elements, and this action will not result in an error. It's just that all intermediate elements will not be defined (their value will be equal to an empty string " "). With this implementation of arrays, the programmer does not need to worry, as in other programming languages, that the index will go beyond the size of the array. If a non-existent array element is accessed, Perl returns a value equal to a null string.

If the perl interpreter is set to display warning messages at run time, if an undefined or non-existent array element is accessed, a message will be displayed that the value of the element is not defined

You can determine the number of elements in an array at any time. To do this, you should use the syntactic construction:

$ #array_name 

... which returns the maximum array index, or -1 if no array is defined. To get the number of elements in an array, add 1 to the return value of this construct, because array indexes in Perl start at 0.

When working with arrays, the most "tedious" procedure may be the procedure for assigning values to the elements of the array. It is good if all the necessary data to populate a large-dimensional array already exists in any text file. You can then assign values to the elements of the array by using the read operation from an external file, but more on that in the next chapter. And if you need to create an array of natural numbers up to and including 1000 in the program? Is it really necessary to write 1000 assignment operators, or to organize a loop in which to make the appropriate assignments, or to create a text file containing these numbers? Thankfully, no! Perl provides a range operation for these situations that you can use in the array designer. For example, to create an array of natural numbers up to 1000, one operator is enough:

@naturalNumbers = (1..1000);

The general syntax of the operation range is as follows:

first number..last number 

It defines a set of numbers (integers or real numbers) that begin with the first_number and do not exceed the last_number, in which the subsequent one is greater than the previous one. This operation is valid not only for numbers, but also for alphanumeric strings, but in this case, an increase of one means an increase by one of the ASCII code of the string character. The following examples show how to use the Range operation on string data:

"a".."c" i Corresponds to: "a", "b", "c"
"BCY".."BDB" # Matches: "BCY", "BCZ", "BDA", "BOB"

This operation is especially useful for specifying integers that start from zero, for example, to represent the day of the month in a date of the form "01.02.2000":

@ day_ofjnonth = ("01".."31");

Array variables and an array element can be substituted into strings bounded by double quotation marks. If the interpreter encounters an array variable in a string, it inserts the values of the array elements into it, separated from each other by spaces. The result of the following statements:

@t = (1..3);
print "Numbers@{m}are integers";

... there will be a line:

Numbers! 2 are integers 

All rules for determining the identifier of a scalar variable when it is substituted into a string are transferred to the array variable.

Because of the ability to substitute an array variable, you can specify a quick solution to the problem of printing the contents of an array. The fact is that if you simply specify an array variable in the print operator, then its elements are displayed in a solid string without spaces between them, which is inconvenient when working with numeric data. If you insert an array variable into a string, spaces are inserted between the array elements when you print it. The following two print operators are:

print @m, "\n"; print "@m\n";

... display the array @m of the previous example in different ways:


Looking up an array element to a string using an index expression is no different than looking up a scalar variable: an array element obtained by an index is a scalar quantity. However, one interesting problem can arise here if the program defines a scalar variable with the same identifier as the array. Will the value of this variable or the value of the corresponding array element be inserted into the string? For example, if the program defines a scalar variable $var and an array of @var (we will discuss why this is possible in section 3.5 of this chapter), then the value of the variable or array element will be inserted into the string "$var [0]".

The correct answer is the value of the element, because when parsing, the interpreter will treat the sequence of characters encountered as a lexeme of the $var[0], and not as the name of the variable $var followed by the character "[". If you want to use the value of the scalar variable $var in a string, you can suggest three ways to solve this problem:

"${var}[0.]" # Curly braces delimit characters considered
# by the interpreter as a whole with the $ symbol. "$var\[0]"
# Backslash delimits identifier
# variable. "$var". "[0]" # String concatenation ("." operation) allows unambiguous
# interpret the variable on the first line.

Sometimes you need to isolate a subset of the elements of an array, which we'll call an array fragment. You can perform it simply, but not effectively: to assign the values of the corresponding elements of the old elements to the elements of some new array, you can use a special Perl construct to select a fragment of the array. If you specify a list of indexes of some elements of the array after the name of the array variable in square brackets, then such a construct will define a fragment of the array, and the indexes do not necessarily have to go in any particular order - they can be set arbitrarily. To select a fragment consisting of sequential elements of the array, you can use the range operation familiar to us. An array fragment is itself an array, and therefore can be used on the right side of the assignment statement. Some examples of creating array fragments are shown below:

@t = (10..19); # Source array:
# (10, 11, 12, 13, 14, 15, 16, 17, 18, 19). @t[0, 2, 4, 6, 8];
# Fragment 1: (10, 12, 14, 16, 18). @t[6, 4, 5, 8, 6];
# Fragment 2: (16, 14, 15, 18, 16). @t[2..4];
# Fragment 3: (12, 13, 14). @t[8, 2..4, 0];
# Fragment 4: (18, 12, 13, 14, 10).

When you select an array fragment, the array variable name that begins with the "@" character is used, whereas when referencing an array element, the variable name prefix is replaced with the "$" character. Here again, the sequential use of the prefix to specify the type of the variable can be traced. An array fragment is an array, and therefore the "@" character should be used.