Search code examples
perlinternals

Where is `use` defined in the perl source code?


Does anyone know where exactly in the source and the compilation stages use is defined in? I didn't see it looking for CORE::GLOBAL::use and I'm unsure of how to dive in looking for it. It's a pretty vague term.


Solution

  • The use syntax is defined in the parser (perly.y). Excerpt:

    |   USE startsub
            { CvSPECIAL_on(PL_compcv); /* It's a BEGIN {} */ }
        BAREWORD BAREWORD optlistexpr ';'
            {
              SvREFCNT_inc_simple_void(PL_compcv);
              utilize($1, $2, $4, $5, $6);
              parser->parsed_sub = 1;
              $$ = NULL;
            }
    

    Not knowing yacc, I have no idea what that's doing.

    The utilize() function is Perl_utilize() from op.c. This code creates a BEGIN block that contains a require. The veop and imop variables may hold opcodes for checking the version or importing the requested elements:

    /* Fake up the BEGIN {}, which does its thing immediately. */
    newATTRSUB(floor,
        newSVOP(OP_CONST, 0, newSVpvs_share("BEGIN")),
        NULL,
        NULL,
        op_append_elem(OP_LINESEQ,
            op_append_elem(OP_LINESEQ,
                newSTATEOP(0, NULL, newUNOP(OP_REQUIRE, 0, idop)),
                newSTATEOP(0, NULL, veop)),
            newSTATEOP(0, NULL, imop) ));
    

    Links into the v5.26.0 source on the Github mirror: