Perl: List, Array
What is List, Array
The words list and array are often used interchangeably.
but technically:
- Perl List roughly means the syntax of array.
- Perl Array is datatype, it is a sequences of values.
now, Perl Array:
- Perl Array can contain any type of values.
- Perl Array can grow or shrink. (it's a dynamic array)
Create a List
- List is enclosed by parenthesis “()”.
- To assign a list to a variable, the variable must have a “@” sign in front.
- To print a list, use the “Dumper” function in the package
Data::Dumper
. 〔see Perl: Print Array or Hashtable〕
@a = (0, 1, 2, 'three', 4, 5, 6, 7); # assigns a list to @a. use Data::Dumper; # loads the list-printing module print '@a is:', Dumper(\@a);
Length
To find the number of elements in a list, use “scalar”.
@a = (4, 5, 6); # a list print scalar(@a); # prints 3. The length. print @a + 0; # prints 3. The + forces a scalar context.
Perl has a “list context” and “scalar context”. How things are evaluated depends on whether the thing is in list or scalar context. “Context” basically means what's adjacent.
When a array is in a scalar context, it returns its length. The function scalar
force it into a scalar context.
Add Element
To add a element, or join two lists, use push(array, new_item)
.
use Data::Dumper; @b = (1, 9); push(@b, 3); # add a element to @b, at the end print Dumper(\@b); # [1, 9, 3]
use Data::Dumper; @a = (1, 9); @b = (3, 4); @c = (); push(@c, @a, @b); # @c is the joined list of @a and @b print Dumper(\@c); # [1, 9, 3, 4]
Get Element
To extract list element, use
@array[index]
@array[index1, index2, etc]
@a = (0, 1, 2, 3, 4); $c = @a[2]; print $c; # 2
use utf8; use Data::Dumper; @a = (0, 1, 2, 3, 4, 5, 6, 7); # get multiple items @b = @a[3, 1, 5]; print Dumper \@b; # [3, 1, 5]
Get sublist (slice)
use Data::Dumper; @a = (0, 1, 2, 'three', 4, 5, 6, 7); @b = @a[1..4]; # the 1..4 creates a range print Dumper \@b; # [1, 2, 'three', 4]
Change Element
To replace parts, just assign them. e.g. $myarray[3] = 'rabbit';
.
use utf8; use Data::Dumper; @a = (0, 1, 2, 3, 4); $a[3] = 99; print Dumper(\@a); # [ 0, 1, 2, 99, 4 ]
Note the dollar sign $
above. This tells Perl that this data is a “scalar”.