Search code examples
perlquine

Explanation for perl quine


I found this quine recently

$a='$a=%c%s%c;printf($a,39,$a,39,10);%c';printf($a,39,$a,39,10);

And I just can't get my head around it. I've found no explanation on google/SO for this particular one, so I'm hoping that someone could explain to me how that thing works :-)


Solution

  • Look at printf parameters and substitute them by hand,

    (39 is single quote, ', and 10 is newline \n when interpreted as %c) so $a which start as

    $a=%c%s%c;printf($a,39,$a,39,10);%c
    

    becomes (replaced chars marked below with ^)

    $a='%s%c;printf($a,39,$a,39,10);%c
       ^ (first %c replaced)
    $a='$a=%c%s%c;printf($a,39,$a,39,10);%c%c;printf($a,39,$a,39,10);%c
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ (%s replaced)
    $a='$a=%c%s%c;printf($a,39,$a,39,10);%c';printf($a,39,$a,39,10);%c
                                           ^ (second %c replaced)
    

    and finally

    $a='$a=%c%s%c;printf($a,39,$a,39,10);%c';printf($a,39,$a,39,10);\n
                                                 (last %c replaced) ^^