Initial Perl version

Ported from the Lua version, plus a first pass at some optimizations.