Just another Perl shrine | |
PerlMonks |
Variations on self-replicationby mstone (Deacon) |
on Sep 24, 2004 at 18:19 UTC ( [id://393620]=CUFP: print w/replies, xml ) | Need Help?? |
Not particularly new, but reasonably cool, this chunk of code:
prints itself as output. The trick revolves around using printf()'s format tokens to make the string recursive (the %s token), and to nest one set of single quotes inside another (the %c tokens around it). The remaining %c tokens are just newlines (ASCII 10), because \n doesn't work inside single quotes. If we strip off the unix-specific header, we get:
which is a little less cluttered, and slightly easier to read. Here's a variant that uses Perl's q() operator, which nests without requiring token substitution:
We can also use the qq() operator (which accepts \n), but this time we have to use token substitution for the dollar signs (ASCII 36). There's no other way to escape them indefinitely:
And finally, here's the simplest possible version, using q() again, with literal newlines:
<update>I didn't mean to suggest that this was the smallest possible Perl quine, though I see how the text could be interpreted that way. All I meant to say was that the above code is the simplest version of this particular self-referential Perl statement. Self-reference and its cousin mutual coreference are much more interesting than simple self-replication, IMO. </update> The trick of using placeholders and substitution is actually one of the deep mysteries of computer programming. The basic idea is simple enough, but the implications (like being able to make infinitely recursive, self-referential strings) are profound.
Back to
Cool Uses for Perl
|
|