Possible Duplicate:
What are quines? Any specific purpose to have them?
How to write a self reproducing code (prints the source on exec)?
please tell me full detail about it.
Possible Duplicate:
What are quines? Any specific purpose to have them?
How to write a self reproducing code (prints the source on exec)?
please tell me full detail about it.
Such a program is called a quine. The existence of a quines in certain classes of language is provable because of Kleene's recursion theorem. There are many examples of quines on Wikipedia for specific languages.
A common approach is to write a program that contains encoded data and prints it twice in two different forms. One of the times it decodes it and prints it, while the other time it prints it in the form in which it must appear in the source code. When the embedded data is an encoded version of the program itself this very nearly produces a quine - although a few adjustments are neccessary to get the output to exactly match the source code. Possible encoding methods include ASCII, hexadecimal, base 64, embedding the program as an escaped string, or any other scheme you wish to use.
For example this Python code when run prints the first line and then some arbitrary data which is encoded in the first line:
data = 'Hello world'
print "data = " + repr(data)
print data
Output:
data = 'Hello world' Hello world
By modifying the contents of the string data
we can preserve that the first line is reproduced in the output and in the remaining lines we can print whatever we want. So we simply change the first line to include a copy of the rest of the program encoded as a Python string:
data = 'print "data = " + repr(data)\nprint data'
print "data = " + repr(data)
print data
Output:
data = 'print "data = " + repr(data)\nprint data' print "data = " + repr(data) print data
A common challenge for programmers is to try to find the shortest possible quine (of non zero length) for a specific language. There is no general algorithm (that runs in a reasonable amount of time) for finding the shortest possible quine in a language. Writing a short quine will require the programmer to find clever approaches.