Quines

From Free media library

{{#switch: |Category = Pages in this category have | This page has }} been marked for eventual deletion.

{{#switch: |Category= They have

| It has}} been identified as reference material per the exclusion guidelines, which the community has decided to exclude from Wikisource (see "Inclusion of reference data on Wikisource"). These works will be phased out gradually; if you have found this page by following a link from another page, please go back and remove that link.

{{#switch::Quines

|Category:Deletion requests/Reference data =
|Wikisource:Scriptorium =  
|

}}


A quine is a computer program that, when executed, prints its own source code.

Here is a list of example quines in various programming languages.

Contents

BASIC

10 LIST

Also because that quine may be considered "cheating", because it directly accesses its own source, here is another quine:

10 C=": PRINT CHR(49)+CHR(48)+CHR(32)+CHR(67)+CHR(61)+CHR(34)+C+CHR(34)+C":
PRINT CHR(49)+CHR(48)+CHR(32)+CHR(67)+CHR(61)+CHR(34)+C+CHR(34)+C

Here is a clearer version, in C64 basic:

10 READ A$:PRINT 10 A$:PRINT 20 "DATA" A$
20 DATA READ A$:PRINT 10 A$:PRINT 20 "DATA" A$

An empty BASIC program compiles in QuickBasic 4.5 (EXE compiles and runs in interpreter) (and probably runs in other BASIC's), and thus can be considered a quine.

Befunge

(Note: There are shorter quines for Befunge, but this one works just as well.)

<>>#"652**:,2+:,,75*,89+2*,>:#,_89+2*,@"

C

#include<stdio.h>
char*i="\\#include<stdio.h>",n='\n',q='"',*p=
"%s%cchar*i=%c%c%s%c,n='%cn',q='%c',*p=%c%c%s%c,*m=%c%c%s%c%c;%s%c",*m=
"int main(){return!printf(p,i+1,n,q,*i,i,q,*i,q,n,q,p,q,n,q,m,q,n,m,n);}"
;int main(){return!printf(p,i+1,n,q,*i,i,q,*i,q,n,q,p,q,n,q,m,q,n,m,n);}

Another one (this should be one single line, and assumes the compiler runs on an ASCII-Machine):

extern printf(char*,...);main(){char*a="extern printf(char*,...);
main(){char*a=%c%s%c;printf(a,34,a,34,10);}%c";printf(a,34,a,34,10);}

or, even shorter (although this is not correct ISO C89, and neither of these conform to the newer ISO C99 standard):

main(){char*a="main(){char*a=%c%s%c;printf(a,34,a,34);}";printf(a,34,a,34);}

This one does not depend on ASCII and uses the C preprocessor for quoting and escaping:

#define T(a) main(){printf(a,#a);}
T("#define T(a) main(){printf(a,#a);}\nT(%s)\n")

As mentioned above, a zero-length program is technically a quine if it can be made to compile into an executable that does nothing (i.e. prints zero characters to stdout). This is possible in C by tweaking the Makefile a bit (because its standard behavior would be not to create an executable).

C++

(Note: linebreaks added for ease of reading)

#include <iostream>
int main(){const char c=',',dq='"',q[]="'",*s[]={"#include <iostream>",
"int main(){const char c=',',dq='","',q[]=",",*s[]={","};std::cout<<s[0]<<std::endl<<s[1]<<dq<<s[2]
<<dq<<q<<dq<<s[3]<<dq<<s[0]<<dq<<c<<dq<<s[1]<<dq<<c<<dq<<s[2]<<dq<<c<<dq<<s[3]<<dq<<c<<dq<<s[4]<<dq
<<s[4]<<std::endl;}"};std::cout<<s[0]<<std::endl<<s[1]<<dq<<s[2]<<dq<<q<<dq<<s[3]<<dq<<s[0]<<dq<<c
<<dq<<s[1]<<dq<<c<<dq<<s[2]<<dq<<c<<dq<<s[3]<<dq<<c<<dq<<s[4]<<dq<<s[4]<<std::endl;}

A slightly shorter version

(Note: linebreaks added for ease of reading)

#include<iostream>
char*i="\"char*i=",*c="\\#include<iostream>",*l=";int main(){std::cout<<c+1<<std::endl<<i+1<<*i<<*c
<<*i<<i+1<<*i<<','<<'*'<<'c'<<'='<<*i<<c[0]<<c<<*i<<','<<'*'<<'l'<<'='<<*i<<l<<*i<<l;}";int main(){
std::cout<<c+1<<std::endl<<i+1<<*i<<*c<<*i<<i+1<<*i<<','<<'*'<<'c'<<'='<<*i<<c[0]<<c<<*i<<','<<'*'
<<'l'<<'='<<*i<<l<<*i<<l;}

C#

(Note: linebreaks added for ease of reading)

using System;
namespace quine
{
  class Program
  {
    [STAThread]
    static void Main(string[] args)
    {
      string s = "using System;{0}namespace quine{0}{2}{0}{1}class Program{0}
{1}{2}{0}{1}{1}[STAThread]{0}{1}{1}static void Main(string[] args){0}{1}{1}{2}{0}{1}{1}{1}
string s = {4}{6}{4};{0}{1}{1}{1}Console.Write(s, Environment.NewLine, {4}{5}t{4}, {4}{2}
{4}, {4}{3}{4}, {4}{5}{4}{4}, {4}{5}{5}{4}, s);{0}{1}{1}{3}{0}{1}{3}{0}{3}";
      Console.Write(s, Environment.NewLine, "\t", "{", "}", "\"", "\\", s);
    }
  }
}

Here's a simpler version that incorporates linebreaks:

class Q
{
    static void Main()
    {
        string s = @"class Q
{0}
    static void Main()
    {0}
        string s = @{2}{3}{2};
        System.Console.Write(s, '{0}', '{1}', '{2}', s);
    {1}
{1}";
        System.Console.Write(s, '{', '}', '"', s);
    }
}

Sans formatting (remove the linebreaks):

class Q{static void Main(){string s="class Q{0}static void 
Main(){0}string s={2}{3}{2};System.Console.Write(s,'{0}',
'{1}','{2}',s);{1}{1}";System.Console.Write(s,'{','}','"',s);}}


Dc

[91PP[dx]93PP]dx


DOS Batch

 @echo off
 %1 %2
 call %0 goto e %%%%
 call %0 goto e %%%%3 echo.%%%%4
 echo :f
 goto f
 :e
 echo.%4@echo off
 echo.%4%31 %32
 echo.%4call %30 goto e %3%3
 echo.%4call %30 goto e %3%33 echo.%3%34
 echo.%4echo :f
 echo.%4goto f
 echo.%4:e
 :f

Emoticon

Z:-O 8-D 8-O ===||8-< :-( 8-Q [8=\ [8~E S:oP :-)

Euphoria

sequence s s = "sequence s s = %s printf(1, s, {34 & s & 34})" printf(1, s, {34 & s & 34})

Haskell

 main=putStr$q++show q;q="main=putStr$q++show q;q="

HQ9+ and HQ9++

Q

(Note: This may be considered cheating because 'Q' instruction 'prints out a copy of the source code of the program'.)

HTML using XMLHTTP

<html><body><pre id="code">.</pre></body><script type="text/javascript">
   var aflac = (window.ActiveXObject)?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();
   aflac.onreadystatechange = aflacStateChange;
   aflac.open("GET", location.href, true); aflac.send(""); 
   function aflacStateChange() {if (aflac.readyState == 4) {addCode(aflac.responseText);}} 
   function addCode(text) {document.getElementById("code").firstChild.nodeValue = text;}
</script></html>

(This may be considered cheating as the source code is simply requested from the server and displayed directly.)

Io

f := method(("f := " ..(Lobby getSlot("f") code) ..("; f")) println); f

Java

(Note: there are no line breaks in the actual code)

class Q{public static void main(String[]a){char q=34;String t="class Q{public static void main(String[]a){char 
q=34;String t=;System.out.println(t.substring(0,62)+q+t+q+t.substring(62));}}";System.out.println(t.substring
(0,62)+q+t+q+t.substring(62));}}

Common Lisp

   (funcall (lambda (x) 
              (append x (list (list 'quote x))))
            '(funcall (lambda (x) 
                         (append x (list (list 'quote x))))))

The shorter one:

:X

Make

foo	=echo\;echo -n foo\\\	=\;make -s getfoo\;echo\;echo open\\\	= \\\(\;echo close\\\	= \\\)\;echo empty\\\	=\;echo tab\\\	= \\\$$\\\(empty\\\)\\\	\\\$$\\\(empty\\\)\;echo \;echo make:\;echo \\\	@echo \\\$$\\\(foo\\\) \\\| /bin/sh\;echo \;echo getfoo:\;echo \\\	echo \\\$$\\\(subst \\\$$\\\$$,\\\$$\\\$$\\\$$\\\$$,\\\$$\\\(subst \\\$$\\\$$,\\\\\\\$$\\\$$,\\\$$\\\(subst \\\',\\\\\\\',\\\$$\\\(subst \\\$$\\\(tab\\\),\\\\\\\$$\\\(tab\\\),\\\$$\\\(subst \\\>,\\\\\\\>,\\\$$\\\(subst \\\<,\\\\\\\<,\\\$$\\\(subst \\\",\\\\\\\",\\\$$\\\(subst \\\;,\\\\\\\;,\\\$$\\\(subst \\\|,\\\\\\\|,\\\$$\\\(subst \\\$$\\\(close\\\),\\\\\\\$$\\\(close\\\),\\\$$\\\(subst \\\$$\\\(open\\\),\\\\\\\$$\\\(open\\\),\\\$$\\\(subst \\\*,\\\\\\\*,\\\$$\\\(subst \\\&,\\\\\\\&,\\\$$\\\(subst \\\`,\\\\\\\`,\\\$$\\\(subst \\\~,\\\\\\\~,\\\$$\\\(subst \\\\,\\\\\\\\,\\\$$\\\(foo\\\)\\\)\\\)\\\)\\\)\\\)\\\)\\\)\\\)\\\)\\\)\\\)\\\)\\\)\\\)\\\)\\\)\;
open	= (
close	= )
empty	=
tab	= $(empty)	$(empty)
make:
	@echo $(foo) | /bin/sh
getfoo:
	echo $(subst $$,$$$$,$(subst $$,\$$,$(subst ',\',$(subst $(tab),\$(tab),$(subst >,\>,$(subst <,\<,$(subst ",\",$(subst ;,\;,$(subst |,\|,$(subst $(close),\$(close),$(subst $(open),\$(open),$(subst *,\*,$(subst &,\&,$(subst `,\`,$(subst ~,\~,$(subst \,\\,$(foo)))))))))))))))))


MATLAB

a='a=%c%s%c;a=sprintf(a,39,a,39);disp(a);';a=sprintf(a,39,a,39);disp(a);


OCaml

(fun s -> Printf.printf "%s %S" s s) "(fun s -> Printf.printf \"%s %S\" s s)"

Pascal

const a='const a=';b='begin write(a,#39,a,#39#59#98#61#39,b,#39#59#10,b) end.';
begin write(a,#39,a,#39#59#98#61#39,b,#39#59#10,b) end.

Remark 1. In the case of a DOS implementation of Pascal the screen output of the program can look somewhat misleading, and it would be appropriate for that case to replace both "#10" in the program by "#13#10" and to insert a CR before the LF at the end of the first line.

Remark 2. The above program can be made even shorter, since both occurrences of ") end." in it can be replaced by ")end." (although this is not good for the legibility). A further shortening can be achieved by skipping both "#10" and writing the program on a single line instead on two ones. After all these changes the program will look as follows (the fact that it continues to be a quine was checked at least in the cases of Turbo Pascal for DOS and Free Pascal for Linux):

const a='const a=';b='begin write(a,#39,a,#39#59#98#61#39,b,#39#59,b)end.';begin write(a,#39,a,#39#59#98#61#39,b,#39#59,b)end.

Another (Borland Pascal and Free Pascal):

const a='const a=;begin write(copy(a,1,8),#39,a,#39,copy(a,9,99)) end.';begin write(copy(a,1,8),#39,a,#39,copy(a,9,99)) end.

Another (Borland Pascal and Free Pascal):

const a:string='const a:string=;begin insert(#39+a+#39,a,16);write(a) end.';begin insert(#39+a+#39,a,16);write(a) end.


Perl

$_=q{$_=q{Q};s/Q/$_/;print};s/Q/$_/;print

Another (note the extra blank line at the end):

print<<''x2,"\n"
print<<''x2,"\n"

And a shell/Perl combo:

perl -le '$n=q{perl -le a$n=q{$x};($_=$n)=~s/\141/\47/g;s/\$x/$n/;printa};($_=$n)=~s/\141/\47/g;s/\$x/$n/;print'

This quine cheats by using the special DATA filehandle to access its own source code:

seek DATA, 0, 0; print <DATA>
__DATA__

This quine cheats by using the eval function to turn data into code at runtime:

$_=q{print"\$_=q{$_};eval"};eval

Universal (and very cheating) sentence that turns any program into a quine. Add this sentence anywhere.

 open ME, $0 and print <ME>;

Just make sure this sentence is the only part in the script that prints. You can also write this like this;

 print <ME> if open ME, $0;

If you are a perl golfer, you should like this one badder. Note 0 is a zero, not a large o.

 open 0 and print <0>;

Perl 6

Just like Perl 5, Perl 6 has a number of ways to turn any programs into a quineuniversal (and very cheating) sentence that turns any programs into a quine. Add this sentence anywhere.

 my $self = open $*PROGRAM_NAME; for =$self { say }

or

 my $self = open $*PROGRAM_NAME; say for =$self;

or

 my $self = slurp $*PROGRAM_NAME; print $self;

or even rubyish

 $*PROGRAM_NAME.slurp.map:{ print };

Note map: is essential in this case because slurp here passes in list context. Damian Conway remarks that you can force scalar context as ~slurp so you can say

 (~slurp $*PROGRAM_NAME).print;

or even

 print ~slurp $*PROGRAM_NAME;

Which appears to be the shortest as of this writing.

PHP

 <?
 $a='chr(60).chr(63).chr(10).chr(36).chr(97).chr(61).chr(39).$a.chr(39).chr(59).chr(10)."echo $a;".chr(10).chr(63).chr(62)';
 echo chr(60).chr(63).chr(10).chr(36).chr(97).chr(61).chr(39).$a.chr(39).chr(59).chr(10)."echo $a;".chr(10).chr(63).chr(62);
 ?>
 
 <?
 $a='<?
 $a=2;
 echo str_replace(1+1,chr(39).$a.chr(39),$a);
 ?>';
 echo str_replace(1+1,chr(39).$a.chr(39),$a);
 ?>

Another:

<?php $c='echo \'<?php $c=\\\'\'.addslashes($c).\'\\\';eval($c) ?>\';';eval($c) ?>

Yet Another:

 This is a quine in PHP.

PL1

(Note: This smallest possible PL/I quine will compile using the OS PL/I V2.3.0 compiler, but requires a left margin of 1 and the COMPILE option to override a rather significant number of severe errors, errors and warnings...)

  %dcl z%z='put edit';proc options(main;q=''''put list(m;do i=1,2;z(q)skip;do j=
  1to 78c=substr(m(i),j;if c=q z(c;z(c;end;z(q',';dcl(c,q)char,m(2)char(99)init(
  '%dcl z%z=''put edit'';proc options(main;q=''''''''put list(m;do i=1,2;z(q)skip;do j=',
  '1to 78c=substr(m(i),j;if c=q z(c;z(c;end;z(q'','';dcl(c,q)char,m(2)char(99)init(',


PostScript

 (dup == {dup cvx exec} pop 8 12 getinterval =)
 dup cvx exec

Prolog

quine:-X='write(quine),put(58),put(45),put(88),put(61),put(39),write(X),put(39),
put(44),write(X).',write(quine),put(58),put(45),put(88),put(61),put(39),write(X),
put(39),put(44),write(X).

Python

a='a=%s;print a%%`a`';print a%`a`

A variant which is four characters shorter:

a='a=%r;print a%%a';print a%a

Another:

b='\\';g='"';p='%';s="b='%s%s';g='%s';p='%s';s=%s%s%s;print s%s(b,b,g,p,g,s,g,p)";print s%(b,b,g,p,g,s,g,p)

And another one that shares the last 61 characters with the previous one (just to show that multiple assignments don't save typing):

b,g,p,s='\\','"','%',"b,g,p,s='%s%s','%s','%s',%s%s%s;print s%s(b,b,g,p,g,s,g,p)";print s%(b,b,g,p,g,s,g,p)

And yet another one, that is slightly more readable and more fun to read:

i = r'"i = r\'" + i + "\'\nprint " + i'
print "i = r\'" + i + "\'\nprint " + i

Ruby

puts <<2*2,2
puts <<2*2,2
2

Another, somewhat less legible, one:

_="puts'_='+_.inspect+';'+_";puts'_='+_.inspect+';'+_

Universal (and very cheating) sentence that turns any programs into a quine. Add this sentence anywhere. See also Perl versions.

File.open($0).readlines.each{|l| puts l};

If you don't want to be stuck with autoboxing, here is the shortest one.

puts open($0).read

Scheme

   ((lambda (x)
           (list x (list (quote quote) x)))
       (quote
           (lambda (x)
               (list x (list (quote quote) x)))))

and the very similar

((λ(λ)`(,λ',λ))
'(λ(λ)`(,λ',λ)))

which uses backquoting instead of list.

Smalltalk

[:s | s, s printString] value: '[s: | s, s printString] value: ' 

Tcl

 puts [join [split "puts \[a{a}]" a] {join [split "puts \[a{a}]" a] }]


TeX

This is TeX, Version 3.141592 (no format preloaded)
(quine.tex \output {\message {\output \the \output \end }\batchmode }\end


VBScript

a="a="":b=left(a,3):c=mid(a,3):msgbox(b+b+c+c)":b=left(a,3):c=mid(a,3):msgbox(b+b+c+c)


Visual FoxPro

 CLEAR
 SET TALK OFF
 SET TEXTMERGE ON
 \CLEAR
 \SET TALK OFF
 \SET TEXTMERGE ON

Machine code (DOS COM file)

The characters below have the same character codes as those printed by the quine. However, they may appear differently here due to formatting. Opening the program in a basic text editor like MS-DOS Edit shows the characters actually printed, proving it is a quine.:

 ´@»&#x01;&#x00;¹&#x12;&#x00;º&#x12;&#x01;Í!´@Í!ô@»&#x01;&#x00;¹&#x12;&#x00;º&#x12;&#x01;Í!´@Í!Ã

The above text is a result of the computer processing the hex instructions of the program as characters. The hex instructions themselves are below. They provide a way to create the executable using a hex editor.

 b4 40 bb 01 00 b9 12 00 ba 12 01 cd 21 b4 40 cd 21 c3 b4 40 bb 01 00 b9 12 00 ba 12 01 cd 21 b4 40 cd 21 c3

There is also a version of that program that is much shorter:

 b4 09 ba 00 01 cd 21 c3 24

but this program does not count as quine as it outputs its code directly, which does not obey the requirement that a quine should not use its own program code as data.

It furthermore does not print the terminator $ (24).

Personal tools