Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How i can find realization of some function in Perl source?

Tags:

perl

For example, i want to find source code for 'print' or 'foreach' operators. I have downloaded Perl source and want to see 'real' code for this operators.

like image 664
helgi Avatar asked Dec 26 '22 17:12

helgi


1 Answers

Perl compiles the source code to a graph called the Opcode Tree. At the same time, this data structure represents the syntax and control flow of your program. To understand opcodes, you may want to start with the Illustrated Perl Guts (illguts).

To find out to what Ops your program was compiled, you call it like so:

  • perl -MO=Concise script.pl – to get the opcodes in their syntax tree
  • perl -MO=Concise,-exec script.pl – the -exec option orders the ops in their execution order instead. Sometimes, this is less confusing.
  • perl -MO=Concise,foo script.pl – dump the ops of the foo subroutine.

A typical opcode looks like:

4 <$> const[PV "007B"] s/FOLD ->5
^  ^  ^                ^      ^
|  |  |                |      The next op in execution order
|  |  |                Flags for this op, documented e.g. in illguts. "s" is
|  |  |                scalar context. After the slash, op-specific stuff
|  |  The actual name of the op, may list further arguments
|  The optype ($: unop, 2: binop, @:listop) – not really useful
The op number

Ops are declared like PP(pp_const). To search for that declaration, use the ack tool, which is an intelligent, recursive grep with Perl regexes. To search all C files and headers in the top direcory of the source, we do:

$ ack 'pp_const' *.c *.h

Output (here without color):

op.c
29: * points to the pp_const() function and to an SV containing the constant
30: * value. When pp_const() is executed, its job is to push that SV onto the

pp_hot.c
40:PP(pp_const)

opcode.h
944:    Perl_pp_const,

pp_proto.h
43:PERL_CALLCONV OP *Perl_pp_const(pTHX);

So it's declared in pp_hot.c, line 40. I tend to do vim pp_hot.c +40 to go there. Then we see the definition:

PP(pp_const)
{
    dVAR;
    dSP;
    XPUSHs(cSVOP_sv);
    RETURN;
}

To understand this, you should get a minimal knowledge of the Perl API, and maybe write a bit of XS.

like image 184
amon Avatar answered Feb 19 '23 10:02

amon