Add Perl port, cribbed mostly from Python.