A Little More on Arrays

Let's say we have an array @a containing six items: ("A", "T", "G", "A", "C", "T").  We might picture it something like this:

0
1
2
3
4
5
@a   
A
T
G
A
C
T
We refer to the entire array as @a. Each item in the array can be referred by using square brackets: $a[0], $a[1], ... $a[5].

There are four operations that add or remove items from the array: push,pop, unshift, and shift. A push operation adds an item on the right end of the array, so push(@a, "G") would result in this:

0
1
2
3
4
5
6
@a     A
T
G
A
C
T
G
The reverse of push is pop. We could say pop(@a) to remove the item we just pushed:

0
1
2
3
4
5
@a    A
T
G
A
C
T
We can also save the item popped into a variable: $x = pop(@a) would result in:
 
0
1
2
3
4
           


@a    A
T
G
A
C

$x   
T
The unshift and shiftoperations are similar to push and pop, but the items are added or removed on the left-hand side of the array rather than the right-hand side. After unshift(@a,"C") we have:
 
0
1
2
3
4
5
@a    C
A
T
G
A
C

Notice that the items have changed places in the array.  After push or pop, $a[0] was still "A" and $a[1] was still"T". But after the unshift, the "A" item is now at location 1 instead of location 0, and the "T" is at location 2; so $a[0] is "C", $a[1] is "A", and $a[2] is "T".

We can remove items from the left with shift, and (if we choose) save them in variables as with pop. After
 $y = shift(@a); $z = shift(@a)
 we would have:
 
0
1
2
3
         


         

@a    T
G
A
C

$y   
C

$z    A