Search code examples
perlquine

How does the following quine work?


According to wikipedia :

A quine is a non-empty computer program which takes no input and produces a copy of its own source code as its only output

I saw this piece of perl code and am not able to figure out how it works.

Save the following line in file /tmp/p and run the file as perl /tmp/p:

Illegal division by zero at /tmp/p line 1.

The output of perl /tmp/p is:

Illegal division by zero at /tmp/p line 1.

How is the code working?


Solution

  • First, try to run it with warnings turned on:

    $ perl -w p
    Unquoted string "at" may clash with future reserved word at p line 1.
    Unquoted string "tmp" may clash with future reserved word at p line 1.
    Argument "tmp" isn't numeric in division (/) at p line 1.
    Argument "at" isn't numeric in division (/) at p line 1.

    The first two warnings are from the compile phase.

    Let's look at the Deparse output:

    $ perl -MO=Deparse p
    'division'->Illegal('zero'->by('at' / 'tmp' / 'line'->p(1)));
    p syntax OK

    In essence, the value of at divided by tmp divided by the return value of another method invocationp is passed as an argument to the method by invoked on the class 'zero'. at and tmp are considered to be strings, and their numeric values are zero. Therefore, at/tmp results in the illegal division by zero error.

    You will get the same error if you change the file's contents to

    Stackoverflow hacker news one at /tmp/p line 1.

    If you are wondering how Illegal division becomes 'division'->Illegal, see indirect object syntax, and avoid using it.