Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
How to write a self-printing program (igoro.com)
18 points by andyjohnson0 on July 17, 2012 | hide | past | favorite | 14 comments


It's most convenient to do this in BASIC (the dialect I remember is MS-BASIC), because it has a command (function?) for listing a program's code:

  10 LIST


First saw this 30 years ago - did it in Basic at the time. Two solutions - the pedantic one, where you include the source in constant declarations, then the code that prints the constants twice, once with declarations around them.

The other - an empty program. Run it - nothing. List it - nothing.


Somehow I think I prefer the latter solution ;)


If the author sees this - "quine" should be capitalized, as it's named after a real person (a philosopher - quite a good one). Like "Volts", for example.

[update] Hmm, although both Wikipedia and GEB use lower case. But in GEB it's lower case because it's a verb (quining). Not sure it's used as a noun - (there are index entries for "Quine" and "quining").

[And edited to add caps as i guess otherwise someone will complain]


I'm not sure there's a real hard and fast rule, but once a word becomes separated from the person, it doesn't really make sense to capitalize it like a proper noun.

Compare "Keynesian economics" with Dr. Guillotine's invention the "guillotine"


OK, so I guess what I am saying is that I do not think it is separated yet. The relationship is very close (because of the precise meaning) and the guy only died a few years ago (well, 12).


Maybe I'm missing something, but is the following valid?

    #!/usr/bin/python2
    print open(__file__).read()
    # do other stuff as well
That is, why not just print the source file, rather than store the code within itself?


If you want the easy-but-legal way out, try this one (but strip out the lines with comments first):

    #Start of program
    #End of program


If the running program has to get its source code from some external source like a file, it's generally not considered a quine (consider a Turing machine -- its state transition function is not written anywhere on the tape).


Wikipedia has a really good article on quines (self-printing programs): http://en.wikipedia.org/wiki/Quine_%28computing%29



What about `function _(){console.log(_+'()');'and other stuff';}()`?


What about a program that reads it's source from it's debug info?


I did this in perl and ran it from bash.

print(system("cat perlQuine.pl"));

Is this cheating?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: