Add Perl version

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