Arrays

Contents | Up | Prev | Next

# 9. Arrays

Arrays are a sequence of variables, whose members can be retrieved and assigned to by using their indices. An index passed to an array may well be, and usually is, another variable.

To refer to the `$i`'th element of the array `@myarray`, one uses the syntax `$myarray[$i]`. This element can be assigned to or its value can be retrieved, with the same notation.

Array indices are whole numbers and the first index is 0. As in the length of a string, the number of elements in an array is bounded only by the amount of available memory the computer has.

The following program prints the primes up to 200:

    $num_primes = 0;

    # Put 2 as the first prime so we won't have an empty array,
    # what might confuse the interpreter
    $primes[$num_primes] = 2;
    $num_primes++;

    MAIN_LOOP:
    for $number_to_check (3 .. 200)
    {
        for $p (0 .. ($num_primes-1))
        {
            if ($number_to_check % $primes[$p] == 0)
            {
                next MAIN_LOOP;
            }
        }

        # If we reached this point it means $number_to_check is not
        # divisable by any prime number that came before it.
        $primes[$num_primes] = $number_to_check;
        $num_primes++;
    }

    for $p (0 .. ($num_primes-1))
    {
        print $primes[$p], ", ";
    }
    print "\n";

The notation `scalar(@myarray)` can be used to refer to the number of elements in an array. This number is equal to the maximal index which was assigned in the array plus one. You will also see the notation `$#myarray` which is equal to the maximal index itself (or -1 if the array is empty).

Thus, for example, the above program could have been written as follows:

    # Put 2 as the first prime so we won't have an empty array,
    # what might confuse the interpreter
    $primes[0] = 2;

    MAIN_LOOP:
    for $number_to_check (3 .. 200)
    {
        for $p (0 .. $#primes)
        {
            if ($number_to_check % $primes[$p] == 0)
            {
                next MAIN_LOOP;
            }
        }

        # If we reached this point it means $number_to_check is not
        # divisable by any prime number that came before it.
        $primes[scalar(@primes)] = $number_to_check;
    }

    for $p (0 .. $#primes)
    {
        print $primes[$p], ", ";
    }
    print "\n";

Contents | Up | Prev | Next