Transcript Slide3,

Arrays and Lists
What is an Array?
• Arrays are linear data structures whose
elements are referenced with
subscripts.
• Just about all programming languages
support arrays.
• Perl’s arrays, however, are more
flexible.
Perl’s Arrays
• Perl’s arrays have no type.
• They can hold:
–
–
–
–
Numbers.
Strings.
References.
Any combination of the above.
• The size is undefined.
– An array grows implicitly and can be shrinked.
Arrays as Lists
• Perl’s arrays are list literals.
• A list literal is an ordered sequence of scalar
values.
• Lists are delimited with parentheses.
• The elements are separated by (,).
• The elements can be scalar literals, scalar
values, or expressions.
List Examples
• Some examples of lists:
–
–
–
–
–
(5)
()
(“x”, 100, “y”, 200)
($sum, “sum”)
(2 * $total, “?” x 20)
Range Operator
• The range operator (..) can be used to specify a
range of scalar literals in a list.
• The step size is always 1.
• Example:
– (0 .. 6)
– (1.5 .. 7)
– (5 .. 3)
• Also works for strings. For example:
– (‘a’ .. ‘z’)
– (‘aa’ .. ‘zz’)
Array Variables
• Array variables begin with @
• There is no connection between $list and
@list.
• Like scalar variables, array variables do not
need to be declared.
• An un-initialized array has the empty list as
its value.
Array Assignments
•
Consider the following sequence of
assignments:
1.
2.
3.
4.
•
@a = (1, 2, 3);
@a = (‘a’, ‘b’, ‘c’, ‘x’);
@a = (3.14);
@a = 1;
Assigning an array to a scalar variable
gives the length.
–
–
@a = (1, 2, 3, 4);
$b = @a;
Multiple Assignments
• Can perform multiple parallel assignments
with lists.
• For example:
–
–
–
–
–
–
($a, $b) = (2, 4);
($a, $b) = (2, 4, 6);
($a, $b, $c) = (2, 4);
($a, $b) = ($b, $a);
($a, @list, $b) = (1, 2, 3, 4, 5, 6);
($first, @list) = @list;
Clearing an Array
• Often one needs to clear an array – i.e. set it
to empty.
• This can be done by either:
– @list = ();
– undef @list;
• This will not work:
– @list = undef;
Referencing Array Elements
• An array’s elements can be assigned and
referenced by attaching subscripts to the
array’s name.
• Subscripts are delimited by ([]).
• The first subscript in every array is 0.
• @ is changed to $ when subscripts are
attached.
– @a → $a[0].
References (cont’d)
•
•
Remember there is no relationship
between $list and @list.
Take for example:
1. $list = “Bob”;
2. @list = (1, 2, 3);
3. $list[1] = 4;
•
What is $list?
Arrays and Bounds
• Accessing an element beyond the last one returns
undef.
– No error message is generated!
• Negative subscripts are allowed in Perl.
– The subscript wraps around.
– What happens if a negative subscript references an
undefined element?
• Assignment beyond the last element implicitly
extends the array:
– e.g. $list[50] = 22;
The Last Index
• Sometimes one needs to know the index of the last
element.
– Especially useful in Perl because arrays can be
extended.
• If the array’s name is @list, then $#list has the
index of the last element.
• The last index can be used to clear an array
– $#list = -1;
• Dynamic arrays can be inefficient, but last index
can be used to set an array to its expected max
length – e.g. $#list = 999;
Slices
•
•
•
A slice is a reference to a subset of an
array.
A slice is specified by the name of an
array followed by a range.
For example:
1.
2.
3.
4.
@a = (1, 2, 3, 4);
@a[4,5] = (5, 6);
@first_3 = @a[0,1,2];
@next_3 = @a[3 .. 5];
foreach Statement
• foreach is an iterative statement for arrays.
• The syntax is:
foreach [scalar_var] (list or array variable) {
...
}
• If [scalar_var] is omitted , then $_ is used.
Some Examples
• foreach $age (@ages) {
$age++;
}
• $count = 17;
foreach $count (0 .. 99) {
$sum += $list[$count];
}
• foreach (@a) {
$sum += $_;
}
List Operators
•
•
•
•
•
•
reverse and sort
chop and chomp
splice
pop and push
unshift and shift
split
Reverse and Sort
• reverse reverses a list.
– e.g. @rnames = reverse @names;
• sort sorts a list of strings.
– e.g. @names = (‘Bob’, ‘Mary’, ‘Fred’);
@sorted_names = sort @names;
• What about @x = (42, 68, 10, 5, 103)?
– @x = sort @x;
Splice
• The splice function provides a powerful tool
for modifying arrays
– It removes a slice of an array and optionally
replaces the removed elements.
• This is difficult to do in other programming
languages.
• splice can take a variable number of
parameters.
– Only the first two are mandatory: the name of
the array and an offset.
Splice Examples
• Assume @list = (1, 2, 3, 4, 5) and @new =
(7, 6).
–
–
–
–
–
splice (@list, 3);
splice (@list, 2, 2);
splice (@list, 2, 2, @new);
splice (@list, 2, 0, @new);
splice (@list, 2, 2, 9, 8, 7);
Push and Pop
• Used to simulate the behavior of a stack.
• push takes an array name and the values to
be added.
– Values are added to the end of the array.
– e.g. push @stack, “Bob”;
push @stack, (9, 11, 13);
• pop removes the “top” (i.e. last) element of
the array.
– $value = pop @stack;
Unshift and Shift
• unshift and shift do the same thing as pop
and push, but to the front of an array.
• shift takes off the first element.
– shift @list;
• unshift adds to the front of an array.
– unshift @list, “Bob”;
– unshift @list, (‘x’, ‘y’);
Split
• split is used to take strings apart.
• Can appear in several forms:
–
–
–
–
split /Pattern/, Expression, Limit;
split /Pattern/, Experssion;
split /Pattern/;
split;
• /Pattern/ is a regular expression.
Split (cont’d)
• Some examples of split:
– @fruit = split /,/, “apples, grapes, lime”, 1;
– @chars = split //, “applepie”;
– $_ = “Peter Z. Yeh”;
($f_name, $m_name, $l_name) = split;