People are ingenious

Simon on 2002-06-18T13:10:35

On the Perl course I'm doing, I give out a lot of programming assignments. Last week, people wrote something to get five names and favourite colours from the user, stored each one into a hash, and then wrote out the hash as a colon-delimited file.

This week, I showed them about split and asked them to write something to read the hash back in, and prompt for a name, then display that user's favourite colour. One of the students - a bright girl - said "Why should I use a hash?" and came up with something like this:

use strict; open IN, "favourites.txt" or die $!;

print "Who do you want to know about? "; my $input = ; chomp $input;

while () { chomp; my ($name, $colour) = split /:/; if ($input eq $name) { print "$name's favourite colour is $colour\n"; } }

What can you say? It's decent code, it fulfils the spec, it just wasn't exactly what I had imagined. Ah, the fun of TMTOWTDI...


But what everyone here wants to know is...

jdavidb on 2002-06-18T13:40:50

A bright girl ... in a Perl class ... is she single?

Re:But what everyone here wants to know is...

Simon on 2002-06-18T16:34:35

Been married for years, much to several people's chagrin.

Re:But what everyone here wants to know is...

jdavidb on 2002-11-08T19:33:15

Retracted.

If it passes the tests...

pdcawley on 2002-06-18T14:24:09

Then it deserves full marks. It's not like it's a terrible algorithm (it might well be faster than the hash based solution...).

Now extend the problem. Ask for multiple names to match. Introduce Benchmark.pm.

Apologies if this is teaching you to suck eggs.

Re:If it passes the tests...

Simon on 2002-06-18T16:36:13

Then it deserves full marks.

It got full marks, for doing the job and being clever than the solution I anticipated.

Now extend the problem. Ask for multiple names to match.

I did something similar: asked for it to report an error for names that weren't in the file. She quickly realised a hash-based solution was more appropriate for that.

Take off points...

jordan on 2002-06-18T15:46:56

for misspelling the word "color".

:-) Don't hit me!