## Lists and Arrays

This lecture notes is based on Prof Doreen De Leon's lectures.

Learning Perl, Chapter 3.

### Definition

• A list is ordered scalar data
• Array: a variable that holds a list
• List literal: representation of the value of a list. Consists of a comma-separated list of values in parentheses
• The empty list: just empty parentheses – ()

#### Examples

```@names=("Amy", "Ben", "Charles", "Dianne");
# Amy Ben Charles Dianne
for(\$i=0; \$i < 4; \$i++) {
print \$names[\$i], " ";
}
print "\n";
```
```# an array of numbers
@grades = (99, 22, 35, 85, 63);
# a mix of numbers and string
@array = (15, "Hi", "hello", 23.5);
print \$array[0], \$array[1], "\n"; # 15Hi
\$name0 = "Amy";
\$name1 = "Ben";
\$name2 = "Charles";
# an array of variables
@names = (\$name0, \$name1, \$name2);
print @names, "\n"; #AmyBenCharles
@names2 = ("Hi!".\$name0, "Hi!".\$name1, "Hi!".\$name2);
print @names2, "\n"; #Hi!AmyHi!BenHi!Charles
```

### Variables

• An @ precedes the name. Same rules for naming as for scalar variables.
• The value of an unassigned array is the empty list, ().

### Accessing Array Elements

• Subscripting similar to C++, with index starting at 0 and ending at one less than the length of the list.
• When accessing an element, @ replaced by \$.
• Like in C++, index values can be integer variables.
• If you try to access an array element beyond the end of the array, `undef` returned
• If you give a value to an element with an index that is out of range, intermediate elements are filled in with a value of undef.
• A negative subscript counts back from the end of the array.
• If you store into an array element that is beyound the end of the array, the array is automatically extended as needed.

#### Examples

```# no need to declare an array
\$num[0] = 11;
\$num[1] = 12;
\$num[2] = 20;
print \$num[1],"\n";
# num is a seperate variable;
\$num = 100;
print \$num,"\n";
\$num[5] = 50;
```
```\$num[0] = 11;
\$num[1] = 12;
\$num[2] = 20;
print \$num[-1], "\n"; # 20
print \$num[-2], "\n"; # 12
\$num[5] = 50;
print \$num[-1], "\n"; # 50
print \$num[-2], "\n"; # undefined
```
```\$num[0] = 11;
\$num[1] = 12;
\$num[2] = 20;
\$num[100] = -55;
\$lastIndex = \$#num; # index of the last element
print \$lastIndex, "\n"; # 100;
print \$num[\$lastIndex], "\n"; # -55;
\$#num=2; # forget about anything after index 2
print @num; #111220
```

### The Range Operator

• Two scalar variables separated by ".." creates list of values starting at the left one up to and including the right one.
• If the right value is less than the left one, get an empty list.
• Incrementing is done by whole numbers, up to and at most the right hand value.
• If left and/or right values are floating point numbers, they are truncated.

#### Examples

```@a = (1..5); # same as (1,2,3,4,5)
print @a; # 12345
print "\n";
@b = (1.1..5.7); # same as before
print @b; # 12345
print "\n";
@c = (1..3, 10..12, 15, 20); # (1,2,3,10,11,12,15,20)
print @c;
print "\n";
@d = ('a'..'e'); #('a','b','c','d',e');
print @d; #abcde
print "\n";
\$x = 10;
\$y = 13;
@e=(\$x..\$y); # (10,11,12,13);
print @e; # 10111213
print "\n";
@f=(5..2); #empty
print @f;
print "\n";
```

### `qw` shortcut

• stands for "quoted words"
• easier to type
• words seperated by white space
• words are single quoted

#### Example

```@a = ('Amy', 'Ben','Charles', 'Dianne');
for(\$i=0; \$i <= \$#a; \$i++) {
print \$a[\$i], " ";
}
print "\n";
# same as @a
@b = qw/ Amy Ben Charles Dianne/;
for(\$i=0; \$i <= \$#b; \$i++) {
print \$b[\$i], " ";
}
#same as @a
print "\n";
@c = qw! Amy Ben Charles Dianne!;
for(\$i=0; \$i <= \$#c; \$i++) {
print \$c[\$i], " ";
}
print "\n";

@c = qw# Amy Ben Charles Dianne#;
@c = qw( Amy Ben Charles Dianne);
@c = qw< Amy Ben Charles Dianne>;
@c = qw[ Amy Ben Charles Dianne];
@c = qw{ Amy Ben Charles Dianne};

```
```\$str1 = "Apple";
\$str2 = "Lemon";
@a = (\$str1, \$str2);
print @a, "\n"; # AppleLemmo
@b =qw/\$str1 \$str2/;
print @b, "\n"; # \$str1\$str2
# single quote
```

### List Assignment

```(\$a, \$b, \$c) = ('Apple', 'Banana', 'Orange');
print \$a, " ",\$b,"\n"; # Apple Banana
(\$a, \$b) = (\$b, \$a); #swap
print \$a, " ",\$b, "\n"; # Banana Apple
(\$a, \$b) = ("Lemon", "Pear", "Mango"); #extra item will be ignored
print \$a, " ",\$b, "\n"; # Lemon Pear
(\$a, \$b) = ("Nactarine"); # \$b is undef
```
```@fruit1 = ('Apple', 'Banana', 'Orange');
@fruit2 = ('Lemon', 'Pear', 'Mango');
\$a = 'Nactarine';
@fruit = (@fruit1, \$a, @fruit2, 'Peach');
for(\$i = 0; \$i < 8; \$i++) {
print \$fruit[\$i], " ";
}
```
```@fruit1 = ('Apple', 'Banana', 'Orange');
@fruit2 = @fruit1; #copy an array
\$fruit2[2] = 'Mango';
print @fruit1;
print "\n";
print @fruit2;
```

### Interpolation of Arrays

• Arrays get interpolated in a string in a similar way to scalar variables. Arrays interpolated with spaces between the elements.

#### Example

```@array = (1,3,5,7,9);
#The array is 13579. No space
print "The array is ", @array, ".\n";
#The array is 1 3 5 7 9. With space
print "The array is @array.\n";
```
```@array = qw(apple orange banana);
\$array= "abc";
print "I like \$array[1].\n"; # I like orange
print "I like \${array}[1].\n"; # I like abc[1].
```
```print "My E-mail address is charles\@abc.com";
```

### Array Operators

• `pop` : takes the last element off of an array and retunrs it.
• `push`: adds an element or a list of elements to an array.
• `shift, unshift`: similar to `pop` and `push`, but do it at the beginning of the array
• `reverse` : return the reverse an array. The orignal array is unchanged.
• `sort`: sort the array in dictionary order (even if the array is an arry of numbers.
```@array = qw(a b c d e);
print "@array\n"; # a b c d e
\$x = pop(@array);
print \$x, "\n"; # e
print "@array\n"; # a b c d
\$y = pop @array;
print \$y, "\n"; #d;
print "@array\n"; # a b c
pop @array;
print "@array\n"; # a b
push(@array, 'h');
print "@array\n"; # a b h
push(@array, 'x', 'y');
print "@array\n"; # a b h x y
push @array, 'A';
print "@array\n"; # a b h x y A
push @array, 'C'..'F';
print "@array\n"; # a b h x y A C D E F
@array1 = qw(1 2 3);
@array2 = qw(2 3 5);
push @array1, @array2;
print "@array1\n"; # 1 2 3 2 3 5
```
```@array = qw(a b c d e);
print "@array\n"; # a b c d e
\$x = shift(@array);
print \$x, "\n"; # a
print "@array\n"; # b c d e
\$y = shift @array;
print \$y, "\n"; #b;
print "@array\n"; # c d e
shift @array;
print "@array\n"; # d e
unshift(@array, 'h');
print "@array\n"; # h d e
unshift(@array, 'x', 'y');
print "@array\n"; # x y h d e
unshift @array, 'A';
print "@array\n"; # A x y h d e
unshift @array, 'C'..'F';
print "@array\n"; # C D E F A x y h d e
@array1 = qw(1 2 3);
@array2 = qw(2 3 5);
unshift @array1, @array2;
print "@array1\n"; # 2 3 5 1 2 3
```
```@array = 2..5;
print @array; #2345
print "\n";
@array2 = reverse(@array);
# or @array2 = reverse @array
print @array; #2345
print "\n";
print @array2; #5432
```
```@names = qw(charles betty amy eve dave);
@sorted = sort(@names);
# or @sorted = sort @names
print "@sorted";
```
```@num = 97..102;
@sorted = sort @num;
# 100 101 102 97 98 99
print "@sorted";
```

### The foreach Control Structure

• Takes a list of values and assigns them one at a time to a scalar variable, executing a block of code with each assignment.
```Syntax:  foreach \$scalar (@list) {
...
}```
• \$scalar is called the control variable.
• Can omit the name of the control variable. Perl substitutes the \$_ variable name.
```@array = qw(2 3 5 7 11 13);
\$sum = 0;
foreach \$number (@array) {
\$sum+=\$number
}
print "The sum is \$sum.\n"; #41
```
```@array = qw(2 3 5 7 11 13);
\$sum = 0;
foreach (@array) {
\$sum+=\$_
}
print "The sum is \$sum.\n"; #41
```

### The Default Variable: `\$_`

• The default for many unary operators and functions.
• If you don't specify a variable, \$_ used.
```\$_ = "hello world";
print;
# hello world
```