General philosophy: Don't sit around wondering about what to do for a quiz, because then you won't think of anything. Instead, think of some specific feature or system and make up a lab exercise for it. You're good at thinking of lab exercises. Try asking questions about common traps, such as those in perltrap, or the things you like to warn people about in your intro classes. Another strategy: Pick some task at random from Perl Cookbook. Another: Reimplement some Unix command. ================================================================ Write a function which accepts a year number, and returns true if the year is a leap year in the Gregorian calendar. (Years are leap years if they are divisible by 4, unless they are century years that are not also divisible by 400. For example, 1888, 1892, and 1896 were leap years, as were 1988, 1992, and 1996; 1700, 1800, and 1900 were not; but 2000 was.) ---------------------------------------------------------------- First, locate the 'perlfunc.pod' file that comes with Perl; this file has an alphabetic listing of all of Perl's built-in functions. (If you can't find it on your system, you can obtain a copy from http://perl.plover.com/perldoc/perlfunc.pod.) Then write a Perl program which can be run from the command line like this perlfunc split and which searches 'perlfunc.pod' for the section about 'split' (or whatever function the user specified) and prints it out. ---------------------------------------------------------------- * Quiz 1 sent 20021016 Write a function, 'center', whose argument is a list of strings, which will be lines of text. 'center' should insert spaces at the beginning of the lines of text so that if they were printed, the text would be centered, and return the modified lines. For example, center("This", "is", "a test of the", "center function"); should return the list: " This", " is", " a test of the", "center function" because if these lines were printed, they would look like: This is a test of the center function ---------------------------------------------------------------- Write a function which splits a string into words. For example: words("Left-handed people can't always find the right ladles.") should return the list ("Left-handed", "people", "can't", "always", "find", "the", "right", "ladles") Note that there's no period on 'ladles', because '.' isn't part of the word. ---------------------------------------------------------------- Write a program which generates an HTML table of contents for a directory of files. It should read the directory, producing a list of the files, and write out a file "toc.html" in that same directory, in the following format: Table of Contents for [Directory Name]

Table of Contents for [Directory Name]

file1
file2
... lastfile
The files should be listed in alphabetic order. The program should accept a command-line argument that tells it what directory to index; if the argument is omitted, it should index the current directory. ---------------------------------------------------------------- * Quiz 11 sent 20030206 Why does Perl have the 'defined' function? If you want to see if a variable contains an undefined value, why not just use this: if ($var == undef) { ... } ---------------------------------------------------------------- Write a function, 'ascending', which accepts a list of strings, and returns true if the strings are in ascending alphabetic order. For example, ascending("These", "strings", "are", "not", "in", "order"); should return false, but ascending("These", "are", "in", "not", "order", "strings"); should return true. ---------------------------------------------------------------- You have a program whose job is to analyze a log file and print a report; the report includes information about how long certain actions have taken to perform. The first version of the program just says something like "13" or "173" or "4957" to indicate how many seconds the action required. This turns out to be onconvenient, because the people reading the report don't find it clear---knowing that something took 4957 seconds is not helpful to them. Write a function, 'format_duration' whose argument is a number, indicating a number of seconds duration, and which returns a string in one of these forms) argument format_duration(argument) should return: 13 "13 sec" 173 "2:53 min" 4957 "1:23 hr" 321495 "3d 17h" You can assume that none of the durations will be more than about two weeks, and that it's OK to use the "3d 17h" format for any very long events. Choose an appropriate method for deciding which format should be used to display a certain time. ---------------------------------------------------------------- The Fourth National Bank of Randalsburg has produced a data file showing all account activity for its savings account. The file looks something like this: 109033745 Schwartz + 3357.94 292992711 Phoenix + 144.88 894372173 McClellan + 182.37 109033745 Schwartz - 92.14 894372173 McClellan + 4290.19 292992711 Phoenix - 200.00 The first column is the account number. The second column is the account holder's name. The third column is '+' for a deposit and '-' for a withdrawal, and the fourth column is the amount of money deposited or withdrawn. The lines are guaranteed to be in chronological order. Write a program which reads such a file and produces a list of the names of all the customers who have ever overdrawn their accounts. ---------------------------------------------------------------- The standard Unix 'tee' utility copies its standard input to its standard output, and also copies the input into a file whose name is specified on the command line. For example ls | tee /tmp/listing displays the output of 'ls' on the terminal, but also puts a copy of the data in /tmp/listing. 'tee' also accepts an optional '-a' argument; if present, it appends to the specified file rather than overwriting it. Implement 'tee' in Perl. ---------------------------------------------------------------- Write a program to manufacture random passwords. It should pick two words at random from a dictionary file. Then it should convert the words to either all-lowercase, all-lowercase-with-initial-capital, or to all-capitals, again at random. Then it should join the two words together with a random punctuation character in between. The dictionary file will have one word per line. The program should ignore any words that have fewer than three or more than four letters. A typical dictionary file can be found in /usr/dict or /usr/share/dict on many Unix systems. If you don't have such a file, make up a test dictionary. Sample outputs: ova:seek Dar/RIPE sigh$cue BONN'Flam Roll^Ida ran|WANE SKI!Kate COMA*MAY tub:SUNG sop>DUMP GOLD^TETE IEEE#Hut ---------------------------------------------------------------- * Quiz 2 sent 20021023 Write a function to compute the time difference, in days, between two dates. The dates will be in the format Wed Oct 16 2002 You may want to investigate the 'timelocal' function for this. It's described in _Learning Perl_ 3rd edition on pages 287-288, or in the on-line documentation for the standard perl 'Time::Local' module. ---------------------------------------------------------------- * Quiz 11 sent 20030206 What's wrong with this code? %hash = ...; while () { chomp; for my $key (keys %hash) { if ($key eq $_) { print "$key: $hash{$key}\n"; } } } (Clubbing someone to death with a loaded Uzi) ---------------------------------------------------------------- * Quiz 11 sent 20030206 What's wrong with this code? @matching_words = grep search_for($_, $text_file), @words; sub search_for { my ($target, $file) = @_; return unless open F, "<", $file; while () { return 1 if index($_, $target) >= 1; } close F; return; } Intended answer: It destroys @words. Other possible criticisms: It closes filehandle F, if F was already open; it performs a wasteful repeated search that would probably be better done with a hash lookup. ---------------------------------------------------------------- * Quiz 12 sent 20030212 Given an array of numbers (say 1 4 2 8 5 7) print out a histogram: * **** ** ******** ***** ******* Now print out a vertical histogram: * * * * * *** * *** * *** ***** ****** ---------------------------------------------------------------- Write a program, 'trickle', which reads data line by line, and emits output at an average rate of ten lines per second, or as close thereto as it can. If any command-line arguments are given to 'trickle', it will take them as the names of files which are to be read and output; if there are no command-line arguments, 'trickle' reads from the standard input. Problem: Requires Time::HiRes. Write a program, called 'trickle'. Its output will be the standard output. Its input will be the standard input, unless one or more files were named on the command line, in which case the input is the contents of the files, in order. It will copy the input to the output unchanged. But it will emit the output lines at an average rate of ten per second, or as close to that rate as is practical. It should also support a command-line flag, '-r', whose argument is a rate at which to emit the output, in lines per second. So the complete calling syntax for the program is trickle [-r rate] [files...] and the rate defaults to 10 and the 'files' default to standard input. If you have it trickle one line per second, you don't need Time::HiRes. ---------------------------------------------------------------- * Quiz 3 sent 20021030 Write a program, 'spoilers-ok'. It will read the quiz-of-the-week email message from the standard input, extract the date that the message was sent, and print a message that says It is okay to send spoilers for this quiz or It is too soon to send spoilers for this quiz. You can send spoilers in another 4 hours 37 minutes. It becomes okay to send spoilers after 60 hours have elapsed from the time the quiz was sent. You can be sure that the 'Date' field of the QOTW email message will always be in the same format. For those unfamiliar with this format: Date: Wed, 23 Oct 2002 16:10:15 -0400 The "16:10:15" is the time of day. "-0400" means that the time of day is in a time zone that is 4 hours behind Greenwich. ---------------------------------------------------------------- Write some program. Send it to address X. Then D distributes programs randomly. Now take the program you got and modify it so that it also does Y. ---------------------------------------------------------------- Decode Usenet multipart binaries ---------------------------------------------------------------- Program to undo the effect of that idiotic www.protware.com protection. http://www.protware.com/e_demo.htm ---------------------------------------------------------------- Log file display: Items appear in the queue and are removed later. Each active item should be displayed on a separate line. But the item's line should not change in its queue lifetime. ---------------------------------------------------------------- ftail Problem: Use of seek() to reset EOF condition is not in the Llama book. ticker similarly. ---------------------------------------------------------------- * Quiz 4 sent 20021106 anagram dictionary. One entry per anagram set, under the alphabetically first item. Others have 'see...': ate ate eat tea eat see 'ate' tea see 'ate' Unless there are only two words in the set, in which case: touristy yttrious yttrious touristy ---------------------------------------------------------------- rhyming dictionary based on CMU pronunciation dict or moby dict Note that moby dict may not be distributed by you. ---------------------------------------------------------------- Here's a program that analyzes an Apache web server log and generates a report. Make it faster. ---------------------------------------------------------------- Program to manufacture palindromes. (Too hard?) ---------------------------------------------------------------- * Quiz 6 sent 20021120 Create a function that will take a list of numbers and format them into a human readable string. my @list = (1, 2, 4, 5, 6, 7, 9, 13, 24, 25, 26, 27); print &stringify_numlist(@list)."\n"; should return 1-2, 4-7, 9, 13, 24-27 Could possibly make it a bit harder by having the function accept lists or arrayrefs or a combo of the two. (Mark Hickman) ---------------------------------------------------------------- Find words in a Boggle grid. (David Jacoby) ---------------------------------------------------------------- Given a list of directory names, recursively search the directories, and emit a report listing all the groups of files that have identical names. (Or content.) (Andrew Savige) ---------------------------------------------------------------- Solve word search puzzles. Solve 'fill in' puzzles. (Given a very sparse crossword grid, and a list of words to be filled in, insert them in their proper places.) (Jason Bucata) ---------------------------------------------------------------- * Quiz 5 sent 20021113 Lay out crossword puzzle grids ---------------------------------------------------------------- * Quiz 9 sent 20021212 Spelling checker. Given a dictionary file and a document, locate the mispelled words. ---------------------------------------------------------------- Referee framework for tic-tac-toe players or yahtzee players. Or mancala. 20040124 Or calculation solitaire. ---------------------------------------------------------------- * Quiz 7 sent 20021127 Fudge percentages to add up to 100% even with rounding. ---------------------------------------------------------------- * Quiz 8 sent 20021211 Bill Gosper's 'acur' puzzle: Find similar puzzles. ---------------------------------------------------------------- Generate the 72 quilt blocks. ---------------------------------------------------------------- Function which, given lower and upper bounds, and possibly some other constraints, produces a regex to match only those integers. For example, regex(12, 47) could return 1[2-9]|[23]\d|4[0-7] ---------------------------------------------------------------- Optimal dartboard layout ---------------------------------------------------------------- * Quiz 10 sent 20030128 Guess-the-animal ---------------------------------------------------------------- Generate odd-side magic squares. (Stanton) ---------------------------------------------------------------- Trivial radioactive decay simulator ---------------------------------------------------------------- Quincunx board simulator ---------------------------------------------------------------- Ascii-art banners (Kevin Pfeiffer) ---------------------------------------------------------------- * Quiz 15 sent 20030618 Clock that divides daytime and nighttime into 12 hours each, regardless of time of year. (Kevin Pfeiffer) ---------------------------------------------------------------- Expand acronyms (Brent Sanger) ---------------------------------------------------------------- Given the tank capacity, and a log of (a) number of gallons of gas put in tank, (b) odometer reading, and (c) gas type, calculate the gas mileage of the various types of gas. Remember that the tank might be full of a mixture of regular and premium. ---------------------------------------------------------------- Word count program that emits chars, words, lines, and pages. Pages are 66 lines long, or are terminated by ^L. Should work like unix 'wc'. ---------------------------------------------------------------- File downloader. Use LWP. It should make a *good* estimate of the amount of time remaining. ---------------------------------------------------------------- Since {$a cmp $b} is the default comparison function for 'sort', why do we need 'cmp' at all? ---------------------------------------------------------------- Given email log file with dates, generate time-series histogram showing list membership. ---------------------------------------------------------------- This program is too slow. Make it faster. (refreport, perlreport, qsummary, etc.?) ---------------------------------------------------------------- Link watcher ---------------------------------------------------------------- Given a list of filenames (or URLs?) produce a list of all the directories in which they reside. For example, given just ('/foo/bar/baz'), generate ('/', '/foo', '/foo/bar'). ---------------------------------------------------------------- Loan interest / mortgage amortization calculator. ---------------------------------------------------------------- Simulate human vs. mechanical shuffling of cards and its effect on bridge hand suit distributions. ---------------------------------------------------------------- * Quiz 13 sent 20030528 Implement 'scan': A directory contains a collection of email messages. Filenames are numbers. ---------------------------------------------------------------- * Quiz 14 sent 20030611 HTML table of contents for a directory ---------------------------------------------------------------- Given an ezmlm log file, generate a histogram showing number of subscribers over time. ---------------------------------------------------------------- 'seq' command ---------------------------------------------------------------- ($a .. $b) generates a list of all integers from $a up to $b, if $b is greater than or equal to $a. If $b is less than $a, why doesn't it count down? ---------------------------------------------------------------- compute critical path, given dependencies and durations. ---------------------------------------------------------------- Find examples of Belady's anomaly ---------------------------------------------------------------- Safe version of 'cp' that first copies the data to a temp file in the target directory, then uses 'rename' to atomically replace the old data with the new. ---------------------------------------------------------------- Given a description of a bunch of redirections we would like to accomplish, say p1 = grep -l blarf p1 stdout -> /some/file p2 = grep 'no such file' p1 stderr -> p2 stdin or p1 = ... p2 = ... p1 stdout -> p2 stdin p2 stdout -> p1 stdin p1 stderr -> /dev/null p2 stderr -> /dev/null emit a shell command line that will accomplish these or an error message that so such line is possible. ---------------------------------------------------------------- Topological sorting ---------------------------------------------------------------- Scale a PPM image by an arbitrary factor r < 1. ---------------------------------------------------------------- It should be possible for the computer to manufacture a list of all valid syllogistic inferences by constructing small examples. For instance, it might hypothesize "some A are B; some B are C; therefore some A are C", and then discover a counterexample, viz. A = {red, yellow}, B = {yellow, blue}, C = {blue, green} and so eliminate that hypothetical rule; rules that escape elimination are valid. Related non-QOTW-question: Is this guaranteed to produce all valid rules? How is this related to the question of finite modules for intuitionistic logic? ---------------------------------------------------------------- Multi-lingual: write a program in at least 2 other languages (scripting or compiled). The program inputs 2 numbers and prints all odd numbers in the ranges specified by the input numbers. At programmer discretion the program can error if 2nd input is less than 1st input or the program can iterate over the range in reverse. Programmer should also write about their impressions of each language. (Randy Sims) ---------------------------------------------------------------- `perldoc -X` uses an index to lookup docs. AFAIK, there is no program that generates such an index. Write one. [no details given. programmer must read the perldoc source to determine the appropriate format of index, etc.] (Randy Sims) ---------------------------------------------------------------- Collaborate with perl-qa list and Phalanx to write some tests... (Randy Sims) ---------------------------------------------------------------- Write a binary calculator that performs logical operations. The program must perform operations manually, parsing string into "bit" and comparing bit by bit. [Goal: demonstrate understanding of logical operations.] (Randy Sims) ---------------------------------------------------------------- Using a subset of operators, implement pure perl versions at least 5 of the following functions: grep, map, chomp, index, rindex, tr, pos, split, join, reverse, readline... [Goal: know the cost of operations.] (Randy Sims) ---------------------------------------------------------------- Implement a virtual assembler that performs only basic operations, storing values in registers, perfroming arithmatic operations, etc. (Randy Sims) ---------------------------------------------------------------- Implement a turing complete language like BrainF*ck or use Parse::RecDescent to implement a batch language. (Randy Sims) ---------------------------------------------------------------- Implement a basic RPN calculator. (Randy Sims) ---------------------------------------------------------------- Write a model memory allocator class. Fixed size and variable size. Also add a method to print a fragmentation map. [Goal: experiment with best fit algoritms.] (Randy Sims) ---------------------------------------------------------------- Write an external sorting routine. (eg. external merge sort) (Randy Sims) ---------------------------------------------------------------- Cribbage hand scoring (John J. Trammell) ---------------------------------------------------------------- Find all the different polygons that can be obtained by vertex-to-vertex cuts of a regular N-gon. ---------------------------------------------------------------- Design an optimal dartboard layout. (No high-scoring regions) ---------------------------------------------------------------- Mobius Syndrome game ---------------------------------------------------------------- BCD arithmetic Chen-Ho arithmetic ---------------------------------------------------------------- Draw pictures of Catalan blob sequences ---------------------------------------------------------------- Minesweeper ---------------------------------------------------------------- Given a quotation and a solution set for an acrosstic puzzle, generate the puzzle. ---------------------------------------------------------------- Find all the distinct ways of coloring the faces of a cube with N colors. ---------------------------------------------------------------- Draw mandelbrot set ---------------------------------------------------------------- Any sequence of N integers contains a nonempty subsequence whose total is a multiple of N. Find it.