You can test the values of Perl variables and perform different actions based on the result. This lets you add sophisticated functionality to your questions like custom feedback or grading functions.
The if Statement
Perl includes several ways to test variables and perform different actions based on the result, but the most fundamental of these methods is the if statement, which has the following syntax:
if (condition)
{do_if_true}
elsif (condition)
{do_if_true}
else
{do_if_false}
where:
- condition is a testable condition, such as
$a > 3
- do_if_true is one or more statements to be performed if the tested condition is true
- do_if_false is one or more statements to be performed if all tested conditions are false
The elsif and else clauses are optional.
Use elsif to test additional conditions; statements will be performed only for the first true condition, not for every true condition.
Use else to specify statements to be performed only if none of the tested conditions are true.
(condition) ? do_if_true : do_if_false
Comparison Operators
You can use the following comparison operators when testing values in your questions. You use different operators depending on whether you want to compare values numerically or textually.
Comparison | Numerical Operator | Example | Text Operator | Example |
---|---|---|---|---|
Equality (=) | == |
|
eq |
|
Inequality (≠) | != |
|
ne |
|
Greater Than (>) | > |
|
gt |
|
Less Than (<) | < |
|
lt |
|
Greater Than or Equal To (≥) | >= |
|
ge |
|
Less Than or Equal To (≤) | <= |
|
le |
|
You can use logical and, or, and not operators to combine or negate test criteria as shown in the following table.
Logic | Operator | Example |
---|---|---|
And | && |
|
Or | || |
|
Not | ! |
|
Examples
The following examples should be inside an <EQN> or <eqn> tag.
# if $x is greater than 5, make it equal to 5
if ($x > 5) {$x = 5};
# if $x is greater than 5, make y = 10; otherwise, make y = x squared
if ($x > 5) {$y = 10} else {$y = x**2};
if ($x == 5) # test whether $x = 5
{
$a = 10; # if so, set $a = 10
$b = 2; # and $b = 2
}
elsif ($x == 4) # if $x ≠ 5, test if $x = 4
{
$a = 8; # if so, set $a = 8
$b = 2; # and $b = 2
}
else # if $x ≠ 5 and $x ≠ 4
{
$a = 0; # set $a = 0
$b = 0; # and $b = 0
}
# if $x equals "lion," make $y equal to "cat"
($x eq 'lion') ? {$y = 'cat'};
Example Multiple-Choice Question With Two Correct Answer Choices
The following table summarizes an actual question.
QID | |
---|---|
Name | |
Mode | Multiple-Choice |
Question |
|
Answer |
|
Display to Students |
$thisanswer==2
and
$ORDERED=3
refer to the third choice in the list. This is
because the WebAssign variables $ORDERED
and
$thisanswer
are indexed differently. While
$ORDERED
starts at 1 for the first item,
$thisanswer
starts at 0.