What is an Array?
Perl uses arrays-or lists-to store a series of items. You could use an array to hold all of the lines in a file, to help sort a list of addresses, or to store a variety of items. We'll look at some simple arrays in this section.An array, in Perl, is an ordered list of scalar data.
Each element of an array is an separate scalar variable with a independent scalar value -- unlike PASCAL or C.
Arrays can therefore have mixed elements, for example
(1,"fred", 3.5)is perfectly valid.
Literal Arrays
Arrays can be defined literally in Perl code by simply enclosing the array elements in parentheses and separating each array element with a comma.For example
(1, 2, 3) ("fred", "albert") () # empty array (zero elements) (1..5) # shorthand for (1,2,3,4,5)
Indexed Arrays
You declare an ordinary indexed array by giving it a name and prefixing it with a@
Values are assigned to arrays in the usual fashion:
@array = (1,2,3); @copy_array = @array; @one_element = 1; # not an error but create the array (1)Arrays can also be referenced in the literal list, for example:
@array1 = (4,5,6); @array2 = (1,2,3, @array1, 7,8);results in the elements of array1 being inserted in the appropriate parts of the list.
Therefore after the above operations
@array2 = (1,2,3,4,5,6,7,8)This means Lists cannot contain other lists elements only scalars allowed.
Elements of arrays are indexed by index:
$array1[1] = $array2[3];Assign ``third'' element of array2 to ``first'' element of array1.
Each array element is a scalar so we reference each array element with
$
.
BIG WARNING:
Array indexing starts from 0 in Perl (like C).
So
@array = (1,2,3,4,5,6,7,8);The index
$array[0]
refers to 1 and $array[5]
refers to 6.
If you assign a scalar to an array the scalar gets assigned the length of the array, i.e:
@array2 = (1,2,3,4,5,6,7,8); $length = @array2; # length = 8 $length = $array2[3]; # length gets ``third'' value # in array i.e 4
Associative Arrays
Associative arrays are a very useful and commonly used feature of Perl.Associative arrays basically store tables of information where the lookup is the right hand key (usually a string) to an associated scalar value. Again scalar values can be mixed ``types''.
We have already been using Associative arrays for name/value pair input to CGI scripts.
Associative arrays are denoted by a verb| When you declare an associative array the key and associated values are listed in consecutive pairs.
So if we had the following secret code lookup:
name | code |
dave | 1234 |
peter | 3456 |
andrew | 6789 |
%lookup = ("dave", 1234, "peter", 3456, "andrew", 6789);The reference a particular value you do:
$lookup{"dave"}You can create new elements by assignments to new keys. E.g.
$lookup{"adam"} = 3845;You do new assignments to old keys also:
# change dave's code $lookup{"dave"} = 7634
0 comments:
Post a Comment