Wednesday, February 15, 2012

On Quines

$ ./quine.pl
#!/usr/bin/perl -w
# Had an idea for an easy way to write a quine. This might be cheating.
use strict;

open(my $fh_in, "<", $0) or

    die "Error: Cannot open file $0: $!";

while (<$fh_in>) {
     print;
}


Did I not get the point?

(Okay, okay, quick explanation after the jump)

First, apologies to the non-programmers out there.

Now. The open() statement opens a file, in this case, the file $0, which in Perl is automatically the name of the current program. So it opens a filehandle to itself. Then the  while loop moves through each line of the file it opened (itself), and prints it to the screen.

Point is, I think usually the point of a quine is to find some tricky way to print the source code of the program, within the program, or at least to just include the source in a string that you just print. I think finding the source file itself and just printing it might be a bit of a cheat.

This is usually much harder with esoteric programming languages.

No comments:

Post a Comment

Due to spam, comments will have to wait for manual moderation :/