Online Learning Applications for Technical English


Home
Syllabus
Assignments

Instructor



Producing Homepages

  1. We can use a foreach loop to step through a list of values.
      foreach $i (1, 2, 3)
      {
        print "This is line $i.\n";
      }
    

    In the first iteration of the loop, the control variable ($i in this example) takes the value 1, in the second iteration 2, and in the last iteration 3.

  2. The if structure will check if a value is 0 or not. A non-zero value will cause the program to run the conditional code. The format is:
      if( value )
      {
        conditional code
      }
    
    
    We can use the if structure to compare two values. The comparison operators are:

    Comparison    for numbers    for strings
    Equal
    ==
    eq
    Not equal
    !=
    ne
    Less than
    <
    lt
    Greater than
    >
    gt
    Less than or equal to
    <=
    le
    Greater than or equal to
    >=
    ge
    Some example expressions:
      35 != 30 + 5          # false
      35 == 35.0            # true
      '35' eq '35.0'        # false (comparing as strings)
      'green' lt 'blue'     # false
      'green' lt 'yellow'   # true
      'abc' eq "abc"        # true
      'abc' eq 'Abc'        # false
    

    We write a comparison as follows (you can use else to provide an alternative choice):

      $answer = 'Tokyo';
    
      if( $user_answer eq $answer )
      {
        print "Correct!\n";
      }
      else
      {
        print "Sorry, the correct answer was: $answer.\n";
      }
    

    Note 1: You must put curly braces around the conditional code.

  3. When the conditional code for an if structure is empty, and there is only conditional code for the else part, it is useful to use an or control structure. For example,
    # If you cannot open the log file, end the program.
      open( LOG, ">>$LOG_FILENAME" )
        or die "Could not create $LOG_FILENAME: $!";
    

    It is the same as:

      if( open( LOG ">>$LOG_FILENAME" ) )
      {
    # Nothing to do - just continue with program.
      }
      else
      {
    # Print an error message and end the program.
        die "Could not create $LOG_FILENAME: $!";
      }
    

[ Back ]