Relational and Logical Operators in Perl

The following relational and logical operators are defined in Perl. The syntax is different for comparing numbers and strings, and it is important not to mix them up.

  1. == equality for numbers, eq equality for strings
  2. != not equal for numbers, ne not equal for strings
  3. < less than for numbers, lt less than for strings
  4. <= less than or equal for numbers, le less than or equal for strings
  5. > greater than for numbers, gt greater than for strings
  6. >= greater than or equal for numbers, ge greater than or equal for strings
  7. && and for numbers, and for strings
  8. || or for numbers, or for strings

Conditional Statements in Perl

The most commonly used conditional statements when writing WebWork questions are

  1. If-then statements:
    if ( 5 == 5 ) { $a = 1; }
    if ( 5 <= 6 ) { $b = 1; }
    if ( "Foo" eq "Foo" ) { }
    
    The first two statements are true, so $a = 1; and $b = 1;. The last statement is true, but no action is taken since it is empty between the curly braces.

  2. If-then-else statements:
    if ( 5 >= 6 ) { 
       $a = 1; 
    } else {
       $a = 2;
    }
    
    The first statement is false, so $a = 2;

  3. If-then-elsif-then-else statements:
    if ( 5 >= 6 ) { 
       $a = 1; 
    } elsif ( "Roy" eq "James" ) {
       $a = 2;
    } else {
       $a = 3;
    }
    
    The first two statements are false, so $a = 3;

  4. Compound statements:
    if ( 5 >= 6 || 7 < 10 ) { 
       $a = 1; 
    } 
    if ( 5 >= 6 && 7 < 10 ) { 
       $b = 1; 
    } 
    
    The first if statement would set $a = 1;, but the second if statement would take no action.

Online References