Tom Kelliher, CS29
Mar. 4, 1997
The program should read the file into a list and then accept queries (name), printing the corresponding phone number or an error message. The program should terminate when EOF is received.
Keys:
Design of pseudo-code.
A working program:
#!/usr/contrib/bin/perl -w # upcase.pl if (!open(FILE1, ">file1")) { die "Couldn't open file1"; } if (!open(FILE2, ">file2")) { die "Couldn't open file2"; } $line = <STDIN>; while ($line) { $line =~ tr/a-z/A-Z/; print $line; print FILE1 $line; print FILE2 $line; $line = <STDIN>; } close(FILE1); close(FILE2); exit 0;
Keys:
Tom:946-3544: Mary:946-1234: Joe:946-5678:
&&
(logical and) operator and compound conditions.
Design of Pseudo-code.
A working program:
#!/usr/contrib/bin/perl -w # database.pl print "Enter file name: "; $file = <STDIN>; chop($file); if (!open(FILE, "<$file")) { die "Couldn't open $file"; } $line = <FILE>; $last = 0; while ($line) { $lines[$last] = $line; $last = $last + 1; $line = <FILE>; } close(FILE); print "Enter a name: "; $name = <STDIN>; while ($name) { chop($name); $i = 0; $found = 0; while (!$found && $i < $last) { if ($lines[$i] =~ /$name/) { $found = 1; @fields = split(/:/, $lines[$i]); print "Phone number: $fields[1]\n\n"; } else { $i = $i + 1; } } if (!$found) { print "Couldn't find $name.\n\n"; } print "Enter a name: "; $name = <STDIN>; } exit 0;