Exercises for Wednesday, October 13, 2004
1. In the following program, each line marked with a "<<<" has a bug.
Briefly describe each bug and the problem it would cause when the
program is run.
#!/bin/csh
set line = $<
echo "
" <<<
while ( "$line" != " " ) <<<
printf \n <<<
foreach word ( `echo $line | sed 's/;/ ;/g'` ) <<<
printf "| " <<<
if ( "$word" == " ; " ) then <<<
printf " | \n"
else
printf $word
endif
end
printf "
\n" <<<
end <<<
echo "
"
2. There are multiple ways of doing just about everything. For
the exercise of building an HTML table from a file containing
semicolon-delimited database records, we suggested that you use
'sed' to expand each record into a list of separate words and
then use a 'foreach' loop to build the rows of the table field
by field. An alternative approach would be to use 'sed' to
iteratively dissect each record into fields. Describe what
each line of the following program does:
#!/bin/csh
set line = "Sally Ann;Smith;26;F"
printf "0 - field = [] ; line = [$line]\n"
set line_number = 1
while ( "$line" != "" )
set field = `echo $line | sed 's/\([^;]*\);.*/\1/'`
set line = `echo $line | sed 's/'"$field"'[;]*\(.*\)/\1/'`
printf "$line_number - field = [$field] ; line = [$line] ; \n"
@ line_number ++
end
3. You can also build records field by field. Here's an example
illustrating how you might do this in a script that interactively
adds a record to a databate table. This version assumes that each
field name is a single word. Rewrite the script to support two
additional features: (i) add code so that the script can handle
multi-word field names and (ii) near the end of the script add code
to display the completed record and prompt the user for a response
(yes or no) that determines whether or not the record is actually
added to the data file for the corresponding table.
% ls account.*
account.fields account.data
% cat account.fields
first;last;age;gender
% cat account.data
Sally;Smith;26;F
% cat insert
#!/bin/csh
# the first and only argument specifies a table
set table = $argv
# grab the field names for the specified table
set fields = ( `cat $table.fields | sed 's/;/ /g'` )
# create an empty record
set record = ""
# build the record field by field
foreach field ( $fields )
# prompt the user for the value of a field
printf "enter $field = "
# append the entered value to the record
set record = "$record;$<"
end
# strip off the leading semicolon and append
# the completed record to the table data
echo $record | sed 's/;//' >> $table.data
% insert account
enter first = Freddy
enter last = Jones
enter age = 21
enter gender = M
% cat account.data
Sally;Smith;26;F
Freddy;Jones;21;M