CIS 24: CGI and Perl Programming for the Web

Class 2 (9/18) Lecture Notes

Topics

  1. Statements, Tokens, & Whitespace
  2. Variables & Literals
  3. Operators & Expressions
  4. Undefined, Null, True, & False
  5. Some More Operators
  6. Functions
  7. Conditionals
  8. Lab: Exercises

Return to CIS 24 home page


  1. Statements, Tokens, & Whitespace
    1. Each of the following lines is a Perl statement:
      $inputline = <STDIN>;
      print ($inputline);

      1. A statement is a task for the Perl interpreter to perform, and is delimited by the semicolon.

      2. A Perl program can be thought of as a collection of statements performed one at a time.

    2. At the most basic level, statements consist of tokens and whitespace.

      1. When the Perl interpreter sees a statement, it breaks it down into smaller pieces of information - tokens.

      2. Whitespace (including linefeeds) between tokens is ignored. However, for the sake of the readability of your code, you'll usually want to put at least a blank space between tokens.

      3. A new statement always starts on a new line, but does not need to end on the same line.

      4. You should also use whitespace to help keep your code readable - indent lines of code that fall within statement blocks - more on this below.

    3. The only Perl lines that can violate the syntax rules for statements are comments. Comments have the following rules:
      • The start of a comment is delimited by the # character
      • A comment can appear on the same line as a statement, but it must be after the statement's semicolon
      • The end of a comment is delimited by a linefeed. If you want to have several lines of comments in a row, each line must start with a #

    Each of the tokens in the above code, as well as many others, will be explained in the following sections.

  2. Variables & Literals
    1. In Perl there are four kinds of variables: scalars, file handles, arrays, and hashes. Tonight we'll discuss scalar variables and file handles, and we'll get to arrays and hashes in later classes.

    2. Scalars are denoted by an initial '$'. The character immediately following the '$' must be a letter or underscore. Numbers can be used as subsequent characters in the name. Variable names are case sensitive, and are limited in length to 255 characters.

    3. You'll use file handles to refer to files that you're reading from - or writing to - in a Perl script. File handle names follow the same rules as scalar variables, except that there is no special first character. It's a standard Perl programming practice to have file handles be all capitals, for example, MYFILE.

    4. There are three special file handles that come "built-in" with Perl, and they don't refer to actual files. They are STDIN, STDOUT, and STDERR. These are called "standard input," "standard output," and "standard error." For now, you can think of all three simply as references to your MS-DOS window. So, when you want to get keyboard input from a user, you'll refer to STDIN. Functions such as "print" automatically send their output to STDOUT unless given special instructions to do otherwise - more on this in a later class.

    5. Unlike many other programming languages, in Perl there is no formal declaration of a variable - you can just start using it. Note that a variable's value is "undefined" until you assign something to it - more on this below.

    6. Another thing that makes Perl different from some other programming languages is that you do not make a special distinction between variables that hold string values vs. those that hold numeric values. A variable can even switch its value type from one to the other. For example:
      $a = 5;
      $a = "hello";

      The first line is an example of a variable holding a numeric literal value - the number 5. The second line is an example of a string literal value - the word hello. For short, these are referred to as numeric variables and string variables.

      Perl can treat variable values differently according to context - for example:

      $a = 1;
      $b = 2;
      print $a + $b; # prints 3
      print "\n";
      print $a . $b; # prints 12

    7. Specifics on numeric variables

      1. All numbers are treated by Perl as floating point values. If you're used to languages where 15/4 = 3 instead of 3.75, then you're used to integer rather than floating point math. On most computers there's a limit of approximately 16 digits for floating point numbers. If a number is longer, it gets truncated.

      2. A good way of dealing with long values is to use exponents, e.g. 8e+01 = 80, 114.6e-01 = 11.46. The largest exponent you can store is about e+308.

      3. Round-off error is a problem with using floating point numbers. An example:
        $value = 9.01e+21 + 0.01 - 9.01e+21;
        print ("first value is ", $value, "\n"); # yields 0
        $value = 9.01e+21 - 9.01e+21 + 0.01;
        print ("second value is ", $value, "\n"); #yields 0.01

      4. Perl also supports octal (base 8) and hexadecimal (base 16) notation. Octal numbers start with 0, and hexadecimal numbers start with 0x. These generally don't have much bearing on CGI programming, so we won't discuss them very much in this course.

    8. Specifics on string variables

      1. There are no length limits on string variables.

      2. Double-quoted strings and the qq operator support variable interpolation and escape characters (see p. 24), single-quoted strings and the q operator do not. Note that you can use whatever character you like to delimit your strings with the q and qq operators - in the example below I used a /

        An example:

        $name = "Mike";
        print "hello $name\n";
        print qq/hello $name\n/;
        print 'hello $name\n';
        print q/hello $name\n/;

      3. A note on variable interpolation: you can use the {} tokens to delimit variables from text, e.g. "the ${number}th value". This way Perl will print the value of $number and not think you mean variable $numberth.

  3. Operators & Expressions
    1. In Perl there are wide variety of operators (you just saw q and qq) - tonight we'll cover the most commonly used ones. Operators perform tasks using operands. For example, in the expression 2 + 4, the plus sign is the operator, and the numbers 2 and 4 are the operands. Operands are also referred to as arguments.

    2. Arithmetic: +, -, *, /, **, % see p. 28
      • Precedence: 1. ** 2. * / % 3. + -
        An example:
        $result = 4 + 2 * 3;
        print $result;
      • Associativity: All are left-to-right associative except for ** and -
        An example:
        $result = 2 ** 3 ** 2;
        print $result;

    3. Assignment: =, +=, -=, *=, /=, %=
      • example: $a *= 2; is the same as $a = $a * 2;
      • The assignment operator "cascades" : e.g. $a = $b = 4;

    4. Angle Operator

      The angle operator - also known as the diamond operator - is used only with file handles. It's used to read a line of input from a file.

      Here's the example again from the start of class, reading a line of input from STDIN:

      $inputline = <STDIN>;
      print ($inputline);

    5. Increment and decrement operators: used to increment the value of an integer by 1. So far you've seen $a = $a + 1 to do this, and $a +=1 to do this. There's also $a++ and ++$a.

      1. Pre-increment:
        $var1 = 43;
        $var2 = ++$var1;
        print $var2;

        $var2 equals 44. $var1 was incremented, and then assigned to $var2

      2. Post-increment:
        $var1 = 43;
        $var2 = $var1++;
        print $var2;

        $var2 equals 43 - $var1 was assigned to $var2, and then $var1 was incremented.

      The decrement operator performs subtraction the same way: $a-- and --$a.

    6. String concatenation
      $string1 = "potato";
      $string2 = "head";
      $string3 = $string1 . $string2;
      print $string3;

      The values of $string1 and $string2 are unchanged. You'll use this one a lot; e.g. getting data from a database and dropping it into a sentence.

      There's also the string concatenation and assignment operator:

      $a = "potato";
      $a .= "head";
      print $a;

    7. Single Argument Operators: all the operators you've seen so far that are used with scalar variables require two arguments, e.g. 2 + 2. The most commonly used single argument operator is unary minus, e.g. -6. See p. 31 of your book for others.

    8. Expressions & Subexpressions

      Formally stated, an expression is a collection of Perl operators and operands yielding a result when evaluated by the Perl interpreter. A Perl statement will contain a single expression. For example, the Perl statement print 1 + 2; contains the function print, the expression 1 + 2, and a semicolon.

      You can have an expression that consists of subexpressions. For example: print (2 * 3) + (4 / 2);

  4. Undefined, Null, True, & False
    1. A variable is undefined if no value has been assigned to it. For example, run the following script with warnings turned on:
      $a = 5;
      $c = $a + $b;
      print $c . "\n";

      Perl warns you that the value of $b is "uninitialized" (which is another word for undefined). Note that this does not break the script. If you try to use a variable that's undefined, Perl pretends its value is null, as it did here.

    2. Perl considers the string value "" as null (this is called an empty string), and the numeric value 0 as null. In the previous example, Perl treats $b as if its value were zero (it chooses 0 instead of the empty string since we're performing a mathematical operation).

    3. What is truth? A common task in programming is to determine whether a condition is true or false. Perl makes this determination based on the following rules (these are on p. 45 of your book):
      • The number 0 is false.
      • the empty string and the string "0" are false.
      • A variable that is undefined is false.
      • Everything else is true.

  5. Some More Operators
  6. Now that we know how Perl recognizes true vs. false conditions, there are more operators we can learn.

    1. Logical operators: && (and), || (or), ! (not)

      These are easiest to explain with examples:

      $a = 5;
      $b = 0;
      print "logical or:\n";
      print $a || $b;
      print "\nlogical not:\n";
      print ! $a;
      print "\nlogical and:\n";
      print $a && $b;

      With the "logical or" operator, Perl looks for at least one "true" value in the arguments supplied. $a is considered "true" since it meets the test of truth outlined above. Perl employs "short-circuit" evaluation with the logical or operator (this means it stops evaluating as soon as it finds a true value). It then returns the value of the last argument that was evaluated - in this case, the value of $a.

      In the "logical not" example, the value of $a is "true", but we're asking for "not $a" which means we're asking for "false." Perl will answer such a request with an empty string.

      In the "logical and" example, we're asking if all of the arguments supplied are true. As with the logical or operator, Perl employs "short circuit" evaluation. This means that if all the arguments are true, it will return the value of the last (right-most) argument, since that is the last one Perl evaluated. If one or more of them is false, it will return the value of the first false value encountered, as it immediately stops evaluating at that point.

    2. Comparison (Relational) Operators

      All of these return true or false, except for the <=> and cmp operators which return 1 if the left-hand argument is greater, 0 if the two arguments are equal, and -1 if the right-hand argument is greater.

      • Numeric: <, >, ==, <=, >=, !=, <=> see p. 43
        Example:
        print 4 > 5; # returns false (an empty string) 
        print "\n";
        print 5 > 4; # returns true (the number one)
        Another example:
        print 4 <=> 3; # returns 1
        print "\n";
        print 4 <=> 4; # returns 0
        print "\n";
        print 3 <=> 4; # returns -1
      • String: lt, gt, eq, le, ge, ne, cmp see p. 44
      • Things to note:
        • string comparisons are alphabetic. For example "b" gt "a" is true.
        • if you use numeric comparison operators on strings, the strings will be evaluated as if they were numbers, and vice versa. For example "a" == "b"; returns true, and so does 2 gt 10
        • don't mix up comparison and assignment operators - don't use = when you mean ==

    3. Two of the bit-manipulation operators look very similar to the logical operators: | and &. These and other bit-manipulation operators are used for base 2 (binary) math. We won't be discussing these, but I wanted to point them out so you don't mix them up with the logical operators.

    4. Using the conditional operators require three operands: a condition to test, a value to be returned when the condition is false, and a value to be returned when the condition is true. For example:
      $var = 5;
      $result = $var == 5 ? 14 : 7;
      print $result;

      This means: If $var equals 5, then $result equals 14; otherwise $result equals 7. In this example, $result equals 14.

    5. There are still more operators: pattern matching, pattern translation, list range, file tests, and others - we'll get to them over the course of the semester. Here's a summary of the ones we've discussed so far:

      OPERATOR SYMBOLS NOTES
      q & qq Operators q qq Variable interpolation; Escape characters; User-defined delimiters
      Arithmetic ** * / % + - Precedence; Associativity
      Assignment = += -= *= /= %= Cascades - e.g. $a = $b = 4;
      Angle <> Used only with file handles
      Increment & Decrement ++ -- Prefix and Postfix forms
      String Concatenation . .=  
      1 Argument - int length lc uc cos rand Used with only a single argument
      Logical && || ! "Short-circuit" evaluation; Returns last expression evaluated
      Numeric Comparison < > == <= >= != <=> Returns true (1) or false (null string); Comparison operator returns 1, 0, or -1
      String Comparison lt gt eq le ge ne cmp Ditto above; Alphabetic comparisons
      Bit-manipulation & | ^ ~ << >> Used on base 2 (binary) numbers
      Conditional x ? y : z if x is true, return y; otherwise, return z

  7. Functions
  8. So far you've seen the "print" function. When the Perl interpreter sees "print" in your code, it invokes the "print" function from the Perl library of functions. Most functions accept an argument, which tell Perl what to do with the invoked function (print accepts an argument consisting of what you want to print). Some functions accept multiple arguments.

    We'll learn plenty of functions over the course of the semester. Here's a few besides print:

  9. Conditionals
    1. Overview

      • if: executes when a specific condition is true
      • if-else: chooses between two alternatives
      • if-elsif-else: chooses between more than two alternatives
      • unless: executes unless a specific condition is true
      • while: repeats a group of statements while a specified condition is true
      • until: repeats a group of statements until a specified condition is true

    2. The if statement

      $number = 5;
      if ($number > 0) {
      	print "the number is greater than zero.\n";
      }

      The part preceding the opening curly bracket is known as the conditional expression. The part within the curly brackets is one or more statements constituting the statement block. When using if, the statement block is executed if the conditional statement yields a true result. The statement block can be empty.

    3. Instead of nothing happening when the conditional expression yields a false result, you may want to specify an alternative action: use if...else
      $number = 0;
      if ($number > 0) {
      	print "the number is greater than zero.\n";
      }
      
      else {
      	print "the number is zero.\n";
      }

    4. To choose between multiple alternatives use if...elsif...else
      $number = -2;
      if ($number > 0 ) {
      	print "the number is greater than zero.\n";
      }
      
      elsif ($number < 0) {
      	print "the number is less than zero.\n";
      }
      
      else {
      	print "the number is zero.\n";
      }

    5. The opposite of the if statement is the unless statement: the statement block is executed if the conditional expression is false.
      $number = 0;
      unless ($number) {
      	print "the expression is false.\n";
      }

    6. To continuously repeat a group of statements while a condition is true, use a while loop.
      $count = 0;
      while ($count <= 5) {
      	print "count is " . $count++ . "\n";
      }

      This will result in the numbers 0 to 5 being printed to your screen. Try it with a pre-increment operator instead.

    7. To repeat a group of statements until a condition is true, use an until loop (i.e. the loop is repeated while the conditional expression yields a false result).
      $count = 0;
      until ($count > 5) {
      	print "count is $count\n";
      	$count++;
      }

      This will result in the same thing as the preceding while loop.

    8. You can use single-line conditionals if your statement block consists of only one statement.
      $name = "mike";
      print ("hello\n") if ($name eq "mike");
      $count = 0;
      print ("the number is $count\n") while ($count++ < 5);

  10. Lab: Exercises
  11. Each of the questions below ask you to write a script. Write your scripts using Windows Notepad. Save them to your floppy disk in the A: drive. Make sure you save them with a .pl file extension. If you do not have a floppy disk, please save your files to the C:\temp directory. Run your scripts from the MS-DOS Prompt as we learned last week.

    Things to remember:

    1. Write a script that reads two lines of input from STDIN (Standard Input), and then prints both lines to the screen.

    2. Write a script that reads a line of input and prints a "1" if the line consists of a non-zero integer, and prints nothing if the line consists of 0 or a string. You must do this without using the conditional operators, if, unless, while, or until!

    3. Write a script that converts miles to kilometers. There are 1.609 kilometers in a mile. The script should:
      • Read an integer from STDIN, which is the distance to be converted (e.g. the user could type in 10)
      • Convert the distance to kilometers (in this example, 16.09 km) and print it to the screen.

    4. Write a script that:
      1. Defines a variable called $password (you can give it whatever value you like)
      2. Prints a message to the screen asking the user to enter a password
      3. Uses standard input to accept what the user types in
      4. Prints a message to the screen indicating whether or not what they typed in matches $password

    5. Write a script that:
      1. Sets the value of a variable called $count to 0
      2. Uses a while loop and the autoincrement operator to increment the value of $count to 5
      3. After each increment, prints a message to the screen indicating the current value of $count

    6. Write a script that:
      1. Prints to the screen "What is 17 plus 26?"
      2. Lets the user type in an answer via STDIN
      3. Uses an until loop to keep asking the user for an answer until he or she enters the correct answer

    7. Write a script that:
      1. Asks the user to type in two different integers via STDIN
      2. Assigns each integer to a variable
      3. If the two numbers are equal, prints a message saying so
      4. If the first number is greater by one, prints a message saying so
      5. If the second number is greater by one, prints a message saying so
      6. If none of the above conditions are true, prints the message "The two numbers are not equal"

Return to CIS 24 home page