Tom Kelliher, CS29
Feb. 20, 1997
Two problems to consider:
Sketch elements:
Write a program which opens a disk file and echoes it, line by line, onto the terminal.
How do we go about solving this problem?
A final solution:
#!/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 for input.
# 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;
Write a program which reads pairs of strings from the terminal, compares the strings dictionary-wise, and then prints out if the strings are equal, the first comes before the second, or vice-versa. The program should terminate when it encounters end-of-file on reading the first string.
How do we solve this problem?
A final solution:
#!/usr/contrib/bin/perl -w
print "Enter first string: ";
$string1 = <STDIN>;
if (!$string1)
{
exit 0;
}
chop($string1);
print "Enter second string: ";
$string2 = <STDIN>;
chop($string2);
while (1)
{
if ($string1 lt $string2)
{
print "$string1 comes before $string2\n\n";
}
elsif ($string1 gt $string2)
{
print "$string1 comes after $string2\n\n";
}
else
{
print "The two strings are the same\n\n";
}
print "Enter first string: ";
$string1 = <STDIN>;
if (!$string1)
{
exit 0;
}
chop($string1);
print "Enter second string: ";
$string2 = <STDIN>;
chop($string2);
}
exit 0;