Hack #101. Learn from Obfuscations

Learn more about Perl from the play of others.

Perl has a reputation for serious play. Think of Perl golf (solving problems in the fewest characters possible), JAPHS (printing a simple message in creative ways), and obfuscation (writing odd code that does surprising things). Though you'd never use these tricks in production code, producing such creative programs requires careful study and exploration—both tricks of good hackers.

Exploring obfuscation can also expand your Perl skills.

Consider an obfuscation I posted at Perl Monks (http://www.perlmonks.org/index.pl?node_id=77619; the link includes a deconstruction and explanation by Guildenstern). It is a non-traditional JAPH that is self-referential. Sort of. The use of a variable called pi, the use of the sin function, and the visual layout of the code all hint at what the output will be. The irony of course is that while the layout helps you know what to expect, it actually hinders understanding.

#!/usr/bin/perl # how to (ab)use substr use warnings; use strict; my $pi='3.14159210535152623346475240375062163750446240333543375062'; substr ($^X,0)= substr ($pi,-6);map{ substr ($^X,$.++,1)=chr( substr ($pi,21,2)+ substr ($pi,$_,2))}(12,28,-18,-6,-10,14);map{$^O=$"x( substr ($pi,-5,2)); substr ($^O,sin(++$a/8)*32+ substr ($pi,-2)/2+1,1)=$_; substr ($^O,sin($a/4)*( substr ($pi,2,2))+ substr ($pi,-7,-5)-1,1)=$_;print"$^O$/";eval($^X.('$b,'x3). substr ($pi,-3,1).'.'. substr ($pi,9,2));}(map{chr($_+ substr ...

Get Perl Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.