Test Perl Variables
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 (=) | == |
$a == 3 |
eq |
$a eq 'red' |
Inequality (≠) | != |
$a != 3 |
ne |
$a ne 'red' |
Greater Than (>) | > |
$a > 3 |
gt |
$a gt 'red' |
Less Than (<) | < |
$a < 3 |
lt |
$a lt 'red' |
Greater Than or Equal To (≥) | >= |
$a >= 3 |
ge |
$a ge 'red' |
Less Than or Equal To (≤) | <= |
$a <= 3 |
le |
$a le 'red' |
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 | && |
$a == 3 && $b eq 'red' |
Or | || |
$a == 3 || $b eq 'red' |
Not | ! |
!($a == 3 || $b eq 'red') |
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 |
Which is a characteristic of jellyfish? <_> |
Answer |
<EQN $ORDERED=1; if ($thisanswer==2) {$ORDERED=3}; ''>Sexual reproduction Exoskeleton Asexual reproduction Respiratory system |
Display to Students |