Arithmetic, Strings, and I/O in Perl

Tom Kelliher, CS29

Feb. 18, 1997

Announcements:

  1. Learning Perl is on reserve in Mack.

  2. Reading:
    1. Perl 5 How-To: 1.1, 1.6, 1.7, 3.2, 3.3, 7.1, 7.2.

    2. Learning Perl: Chs. 2, 4, 6.

  3. Programming assignment:
    Write a program which interactively asks for a file name, then opens and reads the file, line by line. Each line should be echoed to the screen, with a line number and a tab (\t) preceding it. (Advanced: In addition, output the number of words in the file. A word is defined to be a contiguous sequence of non-space characters.)

Outline:

  1. Adding -w to the first line of perl programs.

  2. What is a variable?

  3. Arithmetic.

  4. Strings.

  5. File Input/Output (interactive I/O mixed in through former).

  6. Exercise.

Perl Safety Checks

Use the following as the first line of your perl programs:

#!/usr/contrib/bin/perl -w

The Notion of a Variable

  1. Constants: 5, 3.14, "Hello"

  2. Variables.

  3. Scalar variables in perl: $<varName>

  4. A scalar variable can hold:
    1. An integer: 5, -12

    2. A floating-point number: 3.14159, 12.0e6

    3. A string --- sequence of characters.

    (One at a time.)

Arithmetic

Example:

#!/usr/contrib/bin/perl -w

# This is a small perl program which demonstrates some arithmetic
# operations:
#    o I/O.
#    o Assignment.
#    o Addition and division.
#    o == and < --- numeric comparison.
#
# The program reads n, the number of scores, then reads the n scores, then
# prints the average score.


print "Enter the number of scores: "; # Get the number of scores.
$n = <STDIN>;

if ($n == 0)                    # Error checking.
{
    print "n cannot be zero.\n";
    exit 1;                     # Return, abnormally, to shell.
}

if ($n < 0)                     # More error checking.  Could be combined
{                               # with previous check.
    print "n cannot be negative.";
    exit 1;
}

$sum = 0.0;                     # Initialize.

for ($i = 1; $i <= $n; $i = $i + 1) # Read the n scores.
{
    print "Enter score $i: ";
    $score = <STDIN>;
    $sum = $sum + $score;
}

$average = $sum / $n;           # Compute average.

print "\nThe average score is $average.\n"; # Print result.

exit 0;                         # Return, normally, to shell.

What do the ;'s mean?

Features:

  1. Constants, integers, and floats.

  2. Assignment:
    $i = 1;
    $n = <STDIN>;
    $sum = $sum + $score;
    $average = $sum / $n;
    

  3. I/O:
    print "The average is $average.\n";
    print $average;
    

  4. Arithmetic operators: +, -, *, /, **, %. Precedence and ().

  5. Comparisons: ==, !=, <, <=, >, >=

Strings

Example:

#!/usr/contrib/bin/perl -w

# This is a small perl program which demonstrates some string operations:
#    o I/O.
#    o Assignment.
#    o chop()
#    o Concatentation.
#    o eq --- string comparison.
#
# The program reads a first and last name, then prints the entire name.


print "Enter given name: ";     # Get first name.
$first = <STDIN>;
chop($first);                   # Remove "enter" character (newline) from
                                # end of string.

print "Enter family name: ";    # Get last name.
$last = <STDIN>;
chop($last);

$wholeName = $first . " " . $last; # Concatenate the strings.

print "\nYour name is $wholeName.\n"; # Print the name.

if ($wholeName eq "Tom Kelliher") # String comparison.
{
    print "\nSay, you're Tom Kelliher!\n";
}

exit 0;                         # Return, normally, to shell.

Features:

  1. Literal strings: "<string>". Variable substitution.

  2. Special characters: \n, \\ , \", \t

  3. Assignment:
    $name = <STDIN>;
    $nameAgain = $name;
    $wholeName = $first . " " . $last;
    

  4. I/O:
    $name = <STDIN>;
    print $name;
    print "Your name is $name.\n";
    

  5. chop() --- remove last character from a string:
    $name = <STDIN>;
    chop($name);
    

  6. Concatenation: .

  7. Comparisons: eq, ne, lt, le, gt, ge

  8. The empty string: ""

File I/O

#!/usr/contrib/bin/perl -w

# This is a small perl program which demonstrates some file I/O
# operations:
#    o File handles.
#    o Opening a file for input and checking to see if it opened.
#    o Using an opened file.
#    o Closing a file.
#
# This program interactively reads a file name and then copies the contents
# of that file to the screen.


print "Enter file name: ";      # Get the file name.
$name = <STDIN>;
chop($name);

open(INPUT, $name) ||           # Try to open the file.
    die "Cannot open $name";

print "Contents of $name:\n";

while ($line = <INPUT>)         # Print the file on the screen.
{
    print $line;
}

close(INPUT);                   # Close the file.

exit 0;

Features:

  1. File handles --- convention: UPPERCASE.

  2. Opening a file for input and checking:
    open(<HANDLE>, <filename>) ||
        die "Could not open <filename>";
    

  3. Using the opened file for input:
    $line = <HANDLE>;
    

  4. Closing the file: close(<HANDLE>);

Exercise

Copy the file ~kelliher/pub/arith.pl to your home directory. It is the ``compute an average'' example. Modify it so that it computes the geometric rather than the arithmetic average.



Thomas P. Kelliher
Mon Feb 17 22:29:25 EST 1997
Tom Kelliher