A self printing program is one that produces its own source code when executed.

I first read about self reproducing programs in Douglas Hofstadter's Gödel, Escher, Bach: An Eternal Golden Braid. These programs are essentially "reverse quines" (eniuqs) where the same text is used as both code and data.

The example in the book consists of a eniuq function that, given a text a, prints a("a"), a program statement where the input is doubled as function name and input parameter. The trick is feeding eniuq with its whole definition and execution. This can be tricky indeed in languages like C, due to the escape sequences needed when treating quote operators as text. But for example perl provides q(), an easily quotable quote operator. Thus,

sub eniuq{print $_[ 0 ]."(q(".$_[ 0 ]."))"};
eniuq(q(sub eniuq{print $_[ 0 ]."(q(".$_[ 0 ]."))"};
eniuq))
is a straight port of Hofstadter's example to perl.

Or, adding the shebang for direct shell execution:

#!/usr/bin/perl
sub eniuq{print $_[ 0 ]."(q(".$_[ 0 ]."))"};
eniuq(q(#!/usr/bin/perl
sub eniuq{print $_[ 0 ]."(q(".$_[ 0 ]."))"};
eniuq))

The idea is simple, yet devilish in its cleverness. This is fascinating stuff.

Log in or register to write something here or to contact authors.