Skip to main content

Quine

Quine is an interesting program . It is named after the American philosopher Willard Quine. It means a program could run to output the source code of the program itself. There is a special requirement for Quine is that one cannot read or write files during the execution. Therefore, the following is not Quine.

#!/bin/bash
# You cannot read the file from hard disk
cat $0

In JavaScript

There are many examples of Quine in JavaScript. Here is one that I wrote.

const quote = String.fromCharCode(96);
const codes = `const quote = String.fromCharCode(96);
const codes = {};
console.log(codes.replace("{}",quote+codes+quote));
`;
console.log(codes.replace('{}', quote + codes + quote));

The most important part is that you cannot write backquote character within the string literal. Hence we need to use String.fromCharCode(96) to create a backquote without using the symbol itself.

The follow line print the original program.

console.log(codes.replace('{}', quote + codes + quote));

In Python

There are shorter version in Python. But here is an example similar to the JavaScript example above.

codes = """codes = []
print(codes.replace("[]",chr(34)*3+codes+chr(34)*3,1))
"""
print(codes.replace("[]",chr(34)*3+codes+chr(34)*3,1))