A quine program, or quine, is a program that prints its own source code when executed. A quine must not "step out of itself" by, for example, printing the contents of the file in which it is contained or using introspective capabilities to print its own representation. Instead, it must compute its own source code.
The classic way to create such a program is in two steps:
- Initialize a string variable with a placeholder for the interpolation.
- Print the string and interpolate it into itself .
The trick is choosing the right string. How to do this varies from language to language and depends on variable declaration, the need for semicolons and line breaks, the required quotation marks, and so on. Handling quotation marks is interesting; you have to find a way to indicate that a quotation mark should be printed without actually using one.
Bash
Like most things in Bash, this program uses an interesting quirk. Although single quotes are strong quotes and do not expand anything, the printf octal escape characters as characters with the specified code point:
s='s=\47%s\47;printf "$s" "$s"';printf "$s" "$s"
Python
In Python, the format identifier %r The easiest way is to end the code with a newline character:
s='s=%r;print(s%%s)';print(s%s)
If you want the code without line breaks, you must write the following:
s='s=%r;print(s%%s,sep="")';print(s%s,sep="")
JavaScript
The following JavaScript quines run under node.js. They use console.log, which always adds a new line, so a new line is needed at the end of each script.:
s="s=%j;console.log(s,s)";console.log(s,s)
The following program is also interesting: it does not print its entire representation, but it relies on the fact that functions have a specific representation:
(function a(){console.log('('+a+')()')})()
The next example is close to cheating, as it eval used:
code='var q=unescape("%27");console.log("code="+q+code+q+";eval(code)")';eval(code)
Rust
Rust provides a way to quote an argument in its formatted print macro, but this macro requires the first argument of the print macro to be a string literal! It is therefore best to use the positional argument designator:
fn main(){print!("fn main(){{print!({0:?},{0:?})}}","fn main(){{print!({0:?},{0:?})}}")}
PHP
This PHP program works by saving the source code in a character string and then using this character string with printf The 39 stands for the ASCII character ', to handle the quotation marks in the string correctly:
<?php
$code = '<?php
$code = %c%s%c;
printf($code, 39, $code, 39);
';
printf($code, 39, $code, 39);
HQ9+
Last but not least is HQ9+, which was developed by Cliff Biffle:
Q