Indexed
Arrays (Lists)
A
list is an ordered set of scalar data. List names follow the same
basic rules as for scalars. A reference to a list has the form @foo.
List
literals
List
literals consist of comma-separated values enclosed in parentheses:
(1,2,3)
(“foo”,4.5)
A
range can be represented using a list constructor function (such as
“..”):
(1..9)
= (1,2,3,4,5,6,7,8,9)
($a..$b)
= ($a, $a+1, … , $b-1,$b)
In
the case of string values, it can be convenient to use the
“quote-word” syntax
@a
= (“fred”,”barney”,”betty”,”wilma”);
@a
= qw( fred barney betty wilma );
Accessing
List Elements
List
elements are subscripted by sequential integers, beginning with 0
$foo[5]
is
the sixth element of @foo
The
special variable $#foo
provides
the index value of the last element of @foo.
A subset of elements from a list is called a slice.
@foo[0,1]
is
the same as ($foo[0],$foo[1])
You
can also access slices of list literals:
@foo
= (qw( fred barney betty wilma ))[2,3]
List
operators and functions
Many
list-processing functions operate on the paradigm in which the list
is a stack. The highest subscript end of the list is the “top,”
and the lowest is the bottom.
push
Appends
a value to the end of the list
push(@mylist,$newvalue)
pop
Removes
the last element from the list (and returns it)
pop(@mylist)
shift
Removes
the first element from the list (and returns it)
shift(@mylist)
unshift
Prepends
a value to the beginning of the list
unshift(@mylist,$newvalue)
splice
Inserts
elements into a list at an arbitrary position
splice(@mylist,$offset,$replace,@newlist)
The
reverse
function
reverses the order of the elements of a list
@b
= reverse(@a);
The
sort
function
sorts the elements of its argument as strings in ASCII order. You can
also customize the sorting algorithm if you want to do something
special.
@x
= sort(@y);
The
chomp
function
works on lists as well as scalars. When invoked on a list, it removes
newlines (record separators) from each element of its argument.
No comments :
Post a Comment