Perl hashes are special kinds of arrays consisting of named key/value pairs. You can return a value by specifying the corresponding key.
Perl hash variables are prefixed by the percent sign (%) character. In addition, all Perl variable names must follow these rules:
- Variable names must contain only letters (a-z, A-Z), underscores (_), and numeric digits (0-9).
- The first character of a variable name must be a letter (a-z, A-Z) or underscore (_).
- Variable names are case-sensitive, so myvariable is not the same as MyVariable.
Some variable names are used by WebAssign. These variables are listed in the documentation.
Hashes
Hashes are like a lookup table with a key column and a value column. Instead of specifying a numeric index, you use the key as an index to find the corresponding value.
Key | Value |
---|---|
Mercury | 0.39 |
Venus | 0.72 |
Earth | 1 |
Mars | 1.52 |
Jupiter | 5.20 |
Saturn | 9.54 |
Uranus | 19.18 |
Neptune | 30.06 |
In Perl, you enclose the entire table in parentheses, separate rows with commas, and
use the =>
operator between the key and the value. For example:
%planets = ( 'Mercury' => 0.39 ,
'Venus' => 0.72 ,
'Earth' => 1 ,
'Mars' => 1.52 ,
'Jupiter' => 5.20 ,
'Saturn' => 9.54 ,
'Uranus' => 19.18,
'Neptune' => 30.06 );
You can add a single key/value pair to your hash by specifying the hash variable as a scalar followed by the key name in braces. For example:
$planets{'Neptune'} = 30.06;
=
and not
=>
.To look up a value in a hash variable, you also specify the hash variable as a scalar followed by the key name in braces. For example:
The average orbital distance of Venus is <eqn $planets{'Venus'}> AU.
Example Question Using Hash Variables
The following table summarizes an actual question.
QID | |
---|---|
Name | |
Mode | Fill-in-the-Blank |
Question |
|
Answer |
|
Display to Students |