Wednesday, September 6, 2006

Cats and Perls and Developers

So I spend a good portion of time interviewing job candidates. It can be hard sometimes to find competent individuals, so I am always looking for ways to filter them out.

A few months ago, I started giving a Perl test when people come in to interview. It's not supposed to be hard -- it's just an attempt to see if somebody actually knows Perl, since it seems like everybody puts it on their resume.

I ask people to write a Perl implementation of the UNIX utility cat(1). If they don't know what cat it, well that says something in and of itself. It's only supposed to take a couple of minutes, and those of you who know what cat is will recognize it's a really simple tool.

Here's how I would typically solve the problem, bearing in mind that this is a conservative approach:

#!/usr/bin/perl

if (!defined($ARGV[0]) {
die "Usage: cat <filename>";
}

open INFILE, $ARGV[0] or die "could not open file";
while (my $line = <INFILE>) {
print $line;
}
close INFILE;

That took me about a minute to write. Short and simple. Clear and concise. Perl guys like Dan or Joe or Dmitri might show off a bit and give a more clever answer like the following:

#!/usr/bin/perl
print while <>;

An answer like this demonstrates a particularly good understanding of the language (understanding $_, implicit behavior of "<>" when not providing a file handle, etc.). It's shorter than my implementation because it takes advantage of some of the more obscure aspects of the language (nobody would do it this way in production code because it's too hard to follow).

Then there is what I get from actual interview candidates. Now that you have seen a couple of reasonable approaches to the problem, here is what I got from the last candidate. Note that I am giving him the benefit of the doubt and cleaning up the indentation. The rest if verbatim. I kid you not, this is a real answer from a candidate who claimed to know Perl.

#!/bin/perl
if (#? == 0)
echo Usage cat files [...]
fi

foreach (filename)
if (-f filename)
cat filename
fi
end

Yeah, notice the lack of curly braces and dollar signs? He actually attempts to call the UNIX cat utility from inside his own implementation of cat. It almost would pass as a bash script.

I'll be providing the works of other fine candidates from time to time, as many of them really are pretty funny.