Image of the glider from the Game of Life by John Conway
Skip to content

Perl Obfuscated Code

One of the fun features about Perl is obfuscating code. You can make the simple "Hello World" much more difficult than it should be. This is definitely one of the fun features of programming Perl. For example, from Wikipedia, here is a program that prints out "Just another Perl / Unix hacker" using 32 concurrent processes. How cool is that?

1
2
3
4
@P=split//,".URRUU\c8R";@d=split//,"\nrekcah xinU / lreP rehtona tsuJ";sub p{
@p{"r$p","u$p"}=(P,P);pipe"r$p","u$p";++$p;($q*=2)+=$f=!fork;map{$P=$P[$f^ord
($p{$_})&6];$p{$_}=/ ^$P/ix?$P:close$_}keys%p}p;p;p;p;p;map{$p{$_}=~/^[P.]/&&
close$_}%p;wait until$?;map{/^r/&&< $_>}%p;$_=$d[$q];sleep rand(2)if/\S/;print

Unfortuantely, this program only took 2nd in a obfuscated code contest. According to the author on his website:

I think Felix (the contest judge) made a bad judgement, because the winning program was not nearly as confusing as mine---it was actually very simple. If you fixed the indentation, it was quite straightforward. My program is difficult to understand even if you fix it up with good formatting and reasonable variable names. In the solution file I provided, I expanded it in this way, and it still took me about 2500 words to explain what was going on.

He does provide a more straightened version of the code as a solution to figuring out exactly what the program does and when. He may provide a cleaner, more organized view of the code, but trying to understand the program is left to you. Here it is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
     1  @STATE = split //, ".URRUUxR";
     2  @data = split//,"\nrekcah xinU / lreP rehtona tsuJ";
     3 
     4  sub make_pipe_and_fork {
     5    @pipestate{"r$fhno", "u$fhno"}=(P,P);
     6    pipe "r$fhno", "u$fhno";
     7    ++$fhno;
     8    ($pid *= 2) += $is_child = !fork();
     9    map {
    10      $STATE=$STATE[$is_child ^ ord($pipestate{$_}) & 6];
    11      $pipestate{$_} = (/^$STATE/i ? $STATE : close $_);
    12    } keys %pipestate
    13  }
    14  make_pipe_and_fork;
    15  make_pipe_and_fork;
    16  make_pipe_and_fork;
    17  make_pipe_and_fork;
    18  make_pipe_and_fork;
    19 
    20  map {
    21    $pipestate{$_} =~ /^[P.]/ && close $_
    22  } %pipestate;
    23 
    24  wait until $?;
    25 
    26  map { /^r/ ? < $_> : 1 } %pipestate;
    27 
    28  $_ = $data[$pid];
    29  sleep rand(2) if /\S/;
    30  print

Not bad. Not bad at all.

Post a Comment

Your email is never published nor shared.

Switch to our mobile site