Variables and Arrays

Fundamental to much of what you will do with Perl in WeBWorK involves variables and arrays. All variable names are prefixed with a 1. Thus 2, 3, and 4 are variables while x,y, and z are not, at least usually. More about the exceptions in the pg-language (graphing and answer macros) later. For example,
$x = 12;
$y = ``Hi'';
are simple assignment statements in Perl. Note that every Perl statement must end with a semicolon (;).

Array names start with an 5, thus 6 is an array. Arrays can be initialized in several ways. Two common ways are:

  • @fruit = (``apple'', ``banana'', ``orange'', ``pear'');
  • @fruit = qw(apple banana orange pear);

Each produces the same array (list) of four items: the character strings ``apple'', ``banana'', ``orange'', and ``pear''. The first way is clear, and the second somewhat more convenient using the white space between words to delimit the elements of the array. Of course if one of the entries was to be ``ripe bananas'', you would have to use the first method, or you would produce an array of five elements.

The elements of the array are referred to as the zeroth, first, second, etc. Symbolically, one writes $fruit[0], $fruit[1], and so on. Note the switch from the 7 to the 8.

Arrays can also be specified in rather different ways:

  • @integers = (1 .. 7); [produces (1,2,3,4,5,6,7)]
  • @letters = (B .. F); [produces (B,C,D,E,F)]
  • @rational_numbers = (1.5, 4.5 .. 7.5); [produces (1.5, 4.5, 5.5. 6.5, 7.5)]
  • @real_numbers = (3.14159, @integers); [produces (3.14159, 1, 2, 3, 4, 5, 6, 7)]

The last example may be somewhat surprising. One might realistically expect that @real_numbers is an array with two elements, that latter being an array of seven integers, but no, that is not how Perl works.

Another commonly used technique is to take a slice of an array. Suppose @ALPHABET is the array (A, B, ..., Z) ( or (A .. Z) using the .. construction). Also, suppose that @slice is the array (0, 2, 3, 7).

Then @ALPHABET[@slice] is the array (A, C, D, H), consisting of the 0th, 2nd, 3rd, and 7th elements of the array @ALPHABET. This is a very handy construct for manipulating problems in WeBWorK.