Thursday, August 13, 2009

A Perl Quine

A quine, as popularized by Douglas Hofstadter, is a self-producing program. A program which, upon execution, will output its own source. I finally took the time to write a quine myself and in this blog I will explain my motivations. I have chosen Perl as the language to implement my quine in, although the ideas are language independent.

The first idea I had was something along the line of

#! /usr/bin/env perl

$program = <<'EOP';
#! /usr/bin/env perl

$program = <<'EOP';
#! /usr/bin/env perl

$program = <<'EOP';
.
.
.   
EOP

$program =~ s/^\t//g;
print $program;
EOP

$program =~ s/^\t//g;
print $program;
EOP

$program =~ s/^\t//g;
print $program;

It is an infinite program, so no computer could ever execute it. But it is a quine non the less. It essence is nicely depicted by the following picture.

In this picture the entire ensemble of points is similar to the ensemble with first point removed. (Depicted as a gray point.) The entire ensemble is representing the program, and the ensemble without the first point is the content of the $program variable.

But alas, it is infinite, and although the construction is appealing, it is a bit disappointing. So let's take an other try, staying as close to the original idea as possible. The greatest problem is the moment we start to fill the second $program variable. We been down that road and know it does not lead to anything practical. We will ignore the problem for now and finish our proposal like this.

#! /usr/bin/env perl

my $program = <<'EOP';
#! /usr/bin/env perl

my $program = <<'EOP';
EOP

$program =~ s/^\t//g;
print $program;
EOP

$program =~ s/^\t//g;
print $program;

Now we are almost there. The only difference between the source and it's output is the part which is defined between the EOP markers. But this part is the value of the $program variable. So if we substitute the value of $program at the right place we are done.

The resulting program can be found on google code.

No comments:

Post a Comment