CSCI 344
Quiz 3
Wednesday November 5
You may use any non-living reference. In other words, you can use
books, notes, your solutions to lab assignments, and the web but you cannot communicate with anyone.
Copy your Perl scripts to:
/user/projects/csci344/quizN/USERNAME/quizN
where N is the quiz number and USERNAME is your ecst username.
Put your name in a comment at the top of each file (after the line that contains #!/usr/bin/perl).
1) (5 points) Write a Perl script
that counts the number of lines in the input. If no arguments are
given, use standard input. If one or more arguments are given
assume each is a filename and give the total number of lines in all the
files. Given:
$ wc data
10 10 21 data
$ wc data2
7 7 14 data2
Your script should behave as follows:
$ mywc < data
10
$ mywc data2
7
$ mywc data data2
17
The Perl <> operator makes this very easy. Call your program mywc.
2) (10 points) Write a Perl script that prints the first five lines of standard input:
$ myfirst < file
line 1 of file
line 2 of file
line 3 of file
line 4 of file
line 5 of file
$
If the first argument is a '-' followed by the integer N, print the first N lines of standard input.
$ myfirst -2 < file
line 1 of file
line 2 of file
$
The above will print the first 2 lines of standard input. Name your file myfirst.
3) (10 points) Write a Perl script that prints the last three lines of each of the given files (that is each command line argument is a filename):
$ cat file1
file1: line 1
file1: line 2
file1: line 3
file1: line 4
file1: line 5
file1: line 6
file1: line 7 -- last line
$
$ cat file2
file2: line 1
file2: line 2
file2: line 3
file2: line 4
file2: line 5 -- last line
$
$ mylast file1 file2
file1: line 5
file1: line 6
file1: line 7 -- last line
file2: line 3
file2: line 4
file2: line 5 -- last line
$
Do not allow the user to change the number of lines (like in problem 2). Name your file mylast.
4) (15 points) Write a Perl script that joins files of comma separated values. For example, given the following two files:
$ cat data1.csv
a,b,c
d,e,f
g,h,i
$ cat data2.csv
1,2
3,4
5,6
Running your script should produce the following:
$ myjoin data1.cav data2.csv
a,b,c,1,2
d,e,f,3,4
g,h,i,5,6
Your script should accept any number of files. Assume all the
files have the same number of lines and have the exact comma separated
format as the example files above. Also assume that within a
single file all lines have the same number of values (but between files
lines can have a different number of values as in the above example).
Name your file myjoin.
5) (5 points) Extra credit:
Update the script in (4) so that it prints a meaningful error if
any of the files have a different number of lines or if any of the
files contain lines with a different number of columns. If there
is an error, output only the error. If there is no error the
output should be the same as in (4). Name your file myjoin2.