When I read that book, I saw the C snippet of code which printed itself out using a self-referential printf(). I immediately wrote a quick Perl version, and then tweaked and got a fun little self-ref, a little more Perl-ish in flavor.
#!/usr/bin/perl $q=chr(39);$n=chr(10);$t=chr(96);$a='#!/usr/bin/perl%s$q=chr(39);$n=ch +r(10);$t=chr(96);$a=%s%s%s;$s-sprintf($a,$n,$q,$a,$q,$n);eval$s;%s';$ +s=sprintf($a,$n,$q,$a,$q,$n);eval$s;
This code uses sprintf to generate a string which is the same as its own code. It then evals that string. It's a roundabout method of saying something along the lines of 1 while fork;.

I find it a little more exciting than the alternative and more obvious solution:

#!/usr/bin/perl open(F,"<$0"); undef $/; eval <F>;
Although I find this one easier to maintain ;)

I'd like to explore this area a little more, and have some Perl that mutates itself before the eval. And find some way to not run out of pids. Update: oops, eval != fork so it won't use up pids, but hopefully you get the point. After a few levels deep in the recursion, the program gets painfully slow. Maybe mutate it to the point where it doesn't eval itself anymore after so many levels.

blokhead


In reply to Re: Self Referential Code by blokhead
in thread Self Referential Code by /dev/null

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.