内容

名称

perldebguts - Perl 调试器内部

描述

这不是 perldebug,它告诉你如何使用调试器。本手册页描述了有关调试器内部的低级细节,对于任何不熟悉 Perl 内部的人来说,这些细节都难以理解,甚至是不可能理解的。读者须知。

调试器内部

Perl 在编译时和运行时具有特殊的调试钩子,用于创建调试环境。这些钩子不要与 perlrun 中描述的 perl -Dxxx 命令混淆,该命令仅在按照 Perl 源代码树中 INSTALL 文件中的说明构建了特殊的 Perl 时才可用。

例如,每当你从 DB 包中调用 Perl 的内置 caller 函数时,对应堆栈帧调用的参数都会被复制到 @DB::args 数组中。这些机制通过使用 -d 开关调用 Perl 来启用。具体来说,以下附加功能将被启用(参见 "$^P" in perlvar

请注意,如果 &DB::sub 需要外部数据才能工作,则在没有外部数据的情况下无法进行子程序调用。例如,标准调试器的 &DB::sub 依赖于 $DB::deep 变量(它定义了在强制中断之前可以进入调试器的递归深度级别)。如果未定义 $DB::deep,则即使 &DB::sub 存在,也无法进行子程序调用。

编写自己的调试器

环境变量

PERL5DB 环境变量可用于定义调试器。例如,最小的“工作”调试器(实际上它什么也不做)包含一行

sub DB::DB {}

它可以像这样轻松定义

$ PERL5DB="sub DB::DB {}" perl -d your-script

另一个简短的调试器,稍微有用一些,可以用一行创建

sub DB::DB {print ++$i; scalar <STDIN>}

此调试器打印一个数字,该数字为每个遇到的语句递增,并等待您按下回车键以继续执行下一条语句。

以下调试器实际上很有用

{
  package DB;
  sub DB  {}
  sub sub {print ++$i, " $sub\n"; &$sub}
}

它打印每个子程序调用的序列号和被调用子程序的名称。请注意,&DB::sub 通过使用 package 指令被编译到 DB 包中。

调试器启动时,它会读取您的 rc 文件(在 Unix 下为 ./.perldb~/.perldb),该文件可以设置重要选项。(也可以在此处定义一个子程序 (&afterinit);它在调试器完成自己的初始化后执行。)

读取 rc 文件后,调试器会读取 PERLDB_OPTS 环境变量并使用它来设置调试器选项。此变量的内容被视为 o ... 调试器命令的参数(参见 "perldebug 中的可配置选项")。

调试器内部变量

除了上面提到的文件和子程序相关的变量之外,调试器还维护各种神奇的内部变量。

调试器自定义函数

提供了一些函数来简化自定义。

请注意,任何未在本手册页(或 perldebug 中)记录的变量和函数都被视为仅供内部使用,因此可能会在未经通知的情况下更改。

帧列表输出示例

frame 选项可用于控制帧信息的输出。例如,将此表达式跟踪

$ perl -de 42
Stack dump during die enabled outside of evals.

Loading DB routines from perl5db.pl patch level 0.94
Emacs support available.

Enter h or 'h h' for help.

main::(-e:1):   0
  DB<1> sub foo { 14 }

  DB<2> sub bar { 3 }

  DB<3> t print foo() * bar()
main::((eval 172):3):   print foo() + bar();
main::foo((eval 168):2):
main::bar((eval 170):2):
42

与以下表达式进行对比,一旦设置了 option frame=2

  DB<4> o f=2
               frame = '2'
  DB<5> t print foo() * bar()
3:      foo() * bar()
entering main::foo
 2:     sub foo { 14 };
exited main::foo
entering main::bar
 2:     sub bar { 3 };
exited main::bar
42

为了演示,我们在下面展示了一个费力的列表,该列表是通过将您的 PERLDB_OPTS 环境变量设置为 f=n N 的值,并从命令行运行 perl -d -V 生成的。展示了使用 n 的各种值的示例,让您了解不同设置之间的区别。虽然它可能很长,但这并不是完整的列表,而只是摘录。

  1. entering main::BEGIN
     entering Config::BEGIN
      Package lib/Exporter.pm.
      Package lib/Carp.pm.
     Package lib/Config.pm.
     entering Config::TIEHASH
     entering Exporter::import
      entering Exporter::export
    entering Config::myconfig
     entering Config::FETCH
     entering Config::FETCH
     entering Config::FETCH
     entering Config::FETCH
  2. entering main::BEGIN
     entering Config::BEGIN
      Package lib/Exporter.pm.
      Package lib/Carp.pm.
     exited Config::BEGIN
     Package lib/Config.pm.
     entering Config::TIEHASH
     exited Config::TIEHASH
     entering Exporter::import
      entering Exporter::export
      exited Exporter::export
     exited Exporter::import
    exited main::BEGIN
    entering Config::myconfig
     entering Config::FETCH
     exited Config::FETCH
     entering Config::FETCH
     exited Config::FETCH
     entering Config::FETCH
  3. in  $=main::BEGIN() from /dev/null:0
     in  $=Config::BEGIN() from lib/Config.pm:2
      Package lib/Exporter.pm.
      Package lib/Carp.pm.
     Package lib/Config.pm.
     in  $=Config::TIEHASH('Config') from lib/Config.pm:644
     in  $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
      in  $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from li
    in  @=Config::myconfig() from /dev/null:0
     in  $=Config::FETCH(ref(Config), 'package') from lib/Config.pm:574
     in  $=Config::FETCH(ref(Config), 'baserev') from lib/Config.pm:574
     in  $=Config::FETCH(ref(Config), 'PERL_VERSION') from lib/Config.pm:574
     in  $=Config::FETCH(ref(Config), 'PERL_SUBVERSION') from lib/Config.pm:574
     in  $=Config::FETCH(ref(Config), 'osname') from lib/Config.pm:574
     in  $=Config::FETCH(ref(Config), 'osvers') from lib/Config.pm:574
  4. in  $=main::BEGIN() from /dev/null:0
     in  $=Config::BEGIN() from lib/Config.pm:2
      Package lib/Exporter.pm.
      Package lib/Carp.pm.
     out $=Config::BEGIN() from lib/Config.pm:0
     Package lib/Config.pm.
     in  $=Config::TIEHASH('Config') from lib/Config.pm:644
     out $=Config::TIEHASH('Config') from lib/Config.pm:644
     in  $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
      in  $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/
      out $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/
     out $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
    out $=main::BEGIN() from /dev/null:0
    in  @=Config::myconfig() from /dev/null:0
     in  $=Config::FETCH(ref(Config), 'package') from lib/Config.pm:574
     out $=Config::FETCH(ref(Config), 'package') from lib/Config.pm:574
     in  $=Config::FETCH(ref(Config), 'baserev') from lib/Config.pm:574
     out $=Config::FETCH(ref(Config), 'baserev') from lib/Config.pm:574
     in  $=Config::FETCH(ref(Config), 'PERL_VERSION') from lib/Config.pm:574
     out $=Config::FETCH(ref(Config), 'PERL_VERSION') from lib/Config.pm:574
     in  $=Config::FETCH(ref(Config), 'PERL_SUBVERSION') from lib/Config.pm:574
  5. in  $=main::BEGIN() from /dev/null:0
     in  $=Config::BEGIN() from lib/Config.pm:2
      Package lib/Exporter.pm.
      Package lib/Carp.pm.
     out $=Config::BEGIN() from lib/Config.pm:0
     Package lib/Config.pm.
     in  $=Config::TIEHASH('Config') from lib/Config.pm:644
     out $=Config::TIEHASH('Config') from lib/Config.pm:644
     in  $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
      in  $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/E
      out $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/E
     out $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
    out $=main::BEGIN() from /dev/null:0
    in  @=Config::myconfig() from /dev/null:0
     in  $=Config::FETCH('Config=HASH(0x1aa444)', 'package') from lib/Config.pm:574
     out $=Config::FETCH('Config=HASH(0x1aa444)', 'package') from lib/Config.pm:574
     in  $=Config::FETCH('Config=HASH(0x1aa444)', 'baserev') from lib/Config.pm:574
     out $=Config::FETCH('Config=HASH(0x1aa444)', 'baserev') from lib/Config.pm:574
  6. in  $=CODE(0x15eca4)() from /dev/null:0
     in  $=CODE(0x182528)() from lib/Config.pm:2
      Package lib/Exporter.pm.
     out $=CODE(0x182528)() from lib/Config.pm:0
     scalar context return from CODE(0x182528): undef
     Package lib/Config.pm.
     in  $=Config::TIEHASH('Config') from lib/Config.pm:628
     out $=Config::TIEHASH('Config') from lib/Config.pm:628
     scalar context return from Config::TIEHASH:   empty hash
     in  $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
      in  $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/Exporter.pm:171
      out $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/Exporter.pm:171
      scalar context return from Exporter::export: ''
     out $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
     scalar context return from Exporter::import: ''

在上面显示的所有情况下,行缩进显示了调用树。如果 frame 的第 2 位被设置,则在退出子例程时也会打印一行。如果设置了第 4 位,则会将参数与调用者信息一起打印。如果设置了第 8 位,则即使参数是绑定或引用,也会打印它们。如果设置了第 16 位,则也会打印返回值。

当一个包被编译时,会打印出类似这样的行

Package lib/Carp.pm.

并带有正确的缩进。

调试正则表达式

有两种方法可以启用正则表达式的调试输出。

如果你的 perl 是用 -DDEBUGGING 编译的,你可以在命令行中使用 -Dr 标志,使用 -Drv 可以获得更详细的信息。

否则,可以使用 use re 'debug',它在编译时和运行时都有效。从 Perl 5.9.5 开始,这个 pragma 是词法作用域的。

编译时输出

编译时的调试输出看起来像这样

Compiling REx '[bc]d(ef*g)+h[ij]k$'
size 45 Got 364 bytes for offset annotations.
first at 1
rarest char g at 0
rarest char d at 0
   1: ANYOF[bc](12)
  12: EXACT <d>(14)
  14: CURLYX[0] {1,32767}(28)
  16:   OPEN1(18)
  18:     EXACT <e>(20)
  20:     STAR(23)
  21:       EXACT <f>(0)
  23:     EXACT <g>(25)
  25:   CLOSE1(27)
  27:   WHILEM[1/1](0)
  28: NOTHING(29)
  29: EXACT <h>(31)
  31: ANYOF[ij](42)
  42: EXACT <k>(44)
  44: EOL(45)
  45: END(0)
anchored 'de' at 1 floating 'gh' at 3..2147483647 (checking floating) 
      stclass 'ANYOF[bc]' minlen 7 
Offsets: [45]
	1[4] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 5[1]
	0[0] 12[1] 0[0] 6[1] 0[0] 7[1] 0[0] 9[1] 8[1] 0[0] 10[1] 0[0]
	11[1] 0[0] 12[0] 12[0] 13[1] 0[0] 14[4] 0[0] 0[0] 0[0] 0[0]
	0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 18[1] 0[0] 19[1] 20[0]  
Omitting $` $& $' support.

第一行显示了正则表达式的预编译形式。第二行显示了编译形式的大小(以任意单位表示,通常是 4 字节字),以及为偏移量/长度表分配的总字节数,通常是 4+size*8。下一行显示了第一个匹配节点的标签 id

The

anchored 'de' at 1 floating 'gh' at 3..2147483647 (checking floating) 
      stclass 'ANYOF[bc]' minlen 7 

行(上面分成两行)包含优化器信息。在所示示例中,优化器发现匹配应该包含偏移量为 1 的子字符串 de,以及偏移量在 3 到无穷大之间的子字符串 gh。此外,在检查这些子字符串(以快速放弃不可能的匹配)时,Perl 将先检查子字符串 gh,然后再检查子字符串 de。优化器还可以利用匹配从(第一个 id)开始的字符类,并且没有长度小于 7 个字符的字符串可以匹配。

此行中可能出现的感兴趣字段是

anchored STRING at POS
floating STRING at POS1..POS2

见上文。

matching floating/anchored

首先检查哪个子字符串。

minlen

匹配的最小长度。

stclass TYPE

第一个匹配节点的类型。

noscan

不要扫描找到的子字符串。

isall

表示优化器信息是正则表达式中包含的全部内容,因此根本不需要进入正则表达式引擎。

GPOS

如果模式包含\G,则设置。

plus

如果模式以重复字符开头(如x+y),则设置。

implicit

如果模式以.*开头,则设置。

with eval

如果模式包含 eval 组,例如(?{ code })(??{ code }),则设置。

anchored(TYPE)

如果模式可能只在少数几个地方匹配,其中TYPESBOLMBOLGPOS。请参见下表。

如果已知子字符串仅在行尾匹配,则它后面可以跟$,例如floating 'k'$

优化器特定的信息用于避免在肯定不会匹配的字符串上进入(速度慢的)正则表达式引擎。如果设置了isall标志,即使优化器找到了匹配的合适位置,也可能避免调用正则表达式引擎。

在优化器部分之上是编译后的正则表达式形式的节点列表。每行格式为

id: TYPE OPTIONAL-INFO (next-id)

节点类型

以下是当前可能的类型,以及简短的描述

# TYPE arg-description [regnode-struct-suffix] [longjump-len] DESCRIPTION

# Exit points

END              no         End of program.
SUCCEED          no         Return from a subroutine, basically.

# Line Start Anchors:
SBOL             no         Match "" at beginning of line: /^/, /\A/
MBOL             no         Same, assuming multiline: /^/m

# Line End Anchors:
SEOL             no         Match "" at end of line: /$/
MEOL             no         Same, assuming multiline: /$/m
EOS              no         Match "" at end of string: /\z/

# Match Start Anchors:
GPOS             no         Matches where last m//g left off.

# Word Boundary Opcodes:
BOUND            no         Like BOUNDA for non-utf8, otherwise like
                            BOUNDU
BOUNDL           no         Like BOUND/BOUNDU, but \w and \W are
                            defined by current locale
BOUNDU           no         Match "" at any boundary of a given type
                            using /u rules.
BOUNDA           no         Match "" at any boundary between \w\W or
                            \W\w, where \w is [_a-zA-Z0-9]
NBOUND           no         Like NBOUNDA for non-utf8, otherwise like
                            BOUNDU
NBOUNDL          no         Like NBOUND/NBOUNDU, but \w and \W are
                            defined by current locale
NBOUNDU          no         Match "" at any non-boundary of a given
                            type using using /u rules.
NBOUNDA          no         Match "" betweeen any \w\w or \W\W, where
                            \w is [_a-zA-Z0-9]

# [Special] alternatives:
REG_ANY          no         Match any one character (except newline).
SANY             no         Match any one character.
ANYOF            sv         Match character in (or not in) this class,
                 charclass  single char match only
ANYOFD           sv         Like ANYOF, but /d is in effect
                 charclass
ANYOFL           sv         Like ANYOF, but /l is in effect
                 charclass
ANYOFPOSIXL      sv         Like ANYOFL, but matches [[:posix:]]
                 charclass_ classes
                 posixl

ANYOFH           sv 1       Like ANYOF, but only has "High" matches,
                            none in the bitmap; the flags field
                            contains the lowest matchable UTF-8 start
                            byte
ANYOFHb          sv 1       Like ANYOFH, but all matches share the same
                            UTF-8 start byte, given in the flags field
ANYOFHr          sv 1       Like ANYOFH, but the flags field contains
                            packed bounds for all matchable UTF-8 start
                            bytes.
ANYOFHs          sv:str 1   Like ANYOFHb, but has a string field that
                            gives the leading matchable UTF-8 bytes;
                            flags field is len
ANYOFR           packed 1   Matches any character in the range given by
                            its packed args: upper 12 bits is the max
                            delta from the base lower 20; the flags
                            field contains the lowest matchable UTF-8
                            start byte
ANYOFRb          packed 1   Like ANYOFR, but all matches share the same
                            UTF-8 start byte, given in the flags field

ANYOFHbbm        none bbm   Like ANYOFHb, but only for 2-byte UTF-8
                            characters; uses a bitmap to match the
                            continuation byte

ANYOFM           byte 1     Like ANYOF, but matches an invariant byte
                            as determined by the mask and arg
NANYOFM          byte 1     complement of ANYOFM

# POSIX Character Classes:
POSIXD           none       Some [[:class:]] under /d; the FLAGS field
                            gives which one
POSIXL           none       Some [[:class:]] under /l; the FLAGS field
                            gives which one
POSIXU           none       Some [[:class:]] under /u; the FLAGS field
                            gives which one
POSIXA           none       Some [[:class:]] under /a; the FLAGS field
                            gives which one
NPOSIXD          none       complement of POSIXD, [[:^class:]]
NPOSIXL          none       complement of POSIXL, [[:^class:]]
NPOSIXU          none       complement of POSIXU, [[:^class:]]
NPOSIXA          none       complement of POSIXA, [[:^class:]]

CLUMP            no         Match any extended grapheme cluster
                            sequence

# Alternation

# BRANCH        The set of branches constituting a single choice are
#               hooked together with their "next" pointers, since
#               precedence prevents anything being concatenated to
#               any individual branch.  The "next" pointer of the last
#               BRANCH in a choice points to the thing following the
#               whole choice.  This is also where the final "next"
#               pointer of each individual branch points; each branch
#               starts with the operand node of a BRANCH node.
#
BRANCH           node 1     Match this alternative, or the next...

# Literals

EXACT            str        Match this string (flags field is the
                            length).

# In a long string node, the U32 argument is the length, and is
# immediately followed by the string.
LEXACT           len:str 1  Match this long string (preceded by length;
                            flags unused).
EXACTL           str        Like EXACT, but /l is in effect (used so
                            locale-related warnings can be checked for)
EXACTF           str        Like EXACT, but match using /id rules;
                            (string not UTF-8, ASCII folded; non-ASCII
                            not)
EXACTFL          str        Like EXACT, but match using /il rules;
                            (string not likely to be folded)
EXACTFU          str        Like EXACT, but match using /iu rules;
                            (string folded)

EXACTFAA         str        Like EXACT, but match using /iaa rules;
                            (string folded except MICRO in non-UTF8
                            patterns; doesn't contain SHARP S unless
                            UTF-8; folded length <= unfolded)
EXACTFAA_NO_TRIE str        Like EXACTFAA, (string not UTF-8, folded
                            except: MICRO, SHARP S; folded length <=
                            unfolded, not currently trie-able)

EXACTFUP         str        Like EXACT, but match using /iu rules;
                            (string not UTF-8, folded except MICRO:
                            hence Problematic)

EXACTFLU8        str        Like EXACTFU, but use /il, UTF-8, (string
                            is folded, and everything in it is above
                            255
EXACT_REQ8       str        Like EXACT, but only UTF-8 encoded targets
                            can match
LEXACT_REQ8      len:str 1  Like LEXACT, but only UTF-8 encoded targets
                            can match
EXACTFU_REQ8     str        Like EXACTFU, but only UTF-8 encoded
                            targets can match

EXACTFU_S_EDGE   str        /di rules, but nothing in it precludes /ui,
                            except begins and/or ends with [Ss];
                            (string not UTF-8; compile-time only)

# New charclass like patterns
LNBREAK          none       generic newline pattern

# Trie Related

# Behave the same as A|LIST|OF|WORDS would. The '..C' variants
# have inline charclass data (ascii only), the 'C' store it in the
# structure.

TRIE             trie 1     Match many EXACT(F[ALU]?)? at once.
                            flags==type
TRIEC            trie       Same as TRIE, but with embedded charclass
                 charclass  data

AHOCORASICK      trie 1     Aho Corasick stclass. flags==type
AHOCORASICKC     trie       Same as AHOCORASICK, but with embedded
                 charclass  charclass data

# Do nothing types

NOTHING          no         Match empty string.
# A variant of above which delimits a group, thus stops optimizations
TAIL             no         Match empty string. Can jump here from
                            outside.

# Loops

# STAR,PLUS    '?', and complex '*' and '+', are implemented as
#               circular BRANCH structures.  Simple cases
#               (one character per match) are implemented with STAR
#               and PLUS for speed and to minimize recursive plunges.
#
STAR             node       Match this (simple) thing 0 or more times:
                            /A{0,}B/ where A is width 1 char
PLUS             node       Match this (simple) thing 1 or more times:
                            /A{1,}B/ where A is width 1 char

CURLY            sv 3       Match this (simple) thing {n,m} times:
                            /A{m,n}B/ where A is width 1 char
CURLYN           no 3       Capture next-after-this simple thing:
                            /(A){m,n}B/ where A is width 1 char
CURLYM           no 3       Capture this medium-complex thing {n,m}
                            times: /(A){m,n}B/ where A is fixed-length
CURLYX           sv 3       Match/Capture this complex thing {n,m}
                            times.

# This terminator creates a loop structure for CURLYX
WHILEM           no         Do curly processing and see if rest
                            matches.

# Buffer related

# OPEN,CLOSE,GROUPP     ...are numbered at compile time.
OPEN             num 1      Mark this point in input as start of #n.
CLOSE            num 1      Close corresponding OPEN of #n.
SROPEN           none       Same as OPEN, but for script run
SRCLOSE          none       Close preceding SROPEN

REF              num 2      Match some already matched string
REFF             num 2      Match already matched string, using /di
                            rules.
REFFL            num 2      Match already matched string, using /li
                            rules.
REFFU            num 2      Match already matched string, usng /ui.
REFFA            num 2      Match already matched string, using /aai
                            rules.

# Named references.  Code in regcomp.c assumes that these all are after
# the numbered references
REFN             no-sv 2    Match some already matched string
REFFN            no-sv 2    Match already matched string, using /di
                            rules.
REFFLN           no-sv 2    Match already matched string, using /li
                            rules.
REFFUN           num 2      Match already matched string, using /ui
                            rules.
REFFAN           num 2      Match already matched string, using /aai
                            rules.

# Support for long RE
LONGJMP          off 1 1    Jump far away.
BRANCHJ          off 2 1    BRANCH with long offset.

# Special Case Regops
IFMATCH          off 1 1    Succeeds if the following matches; non-zero
                            flags "f", next_off "o" means lookbehind
                            assertion starting "f..(f-o)" characters
                            before current
UNLESSM          off 1 1    Fails if the following matches; non-zero
                            flags "f", next_off "o" means lookbehind
                            assertion starting "f..(f-o)" characters
                            before current
SUSPEND          off 1 1    "Independent" sub-RE.
IFTHEN           off 1 1    Switch, should be preceded by switcher.
GROUPP           num 1      Whether the group matched.

# The heavy worker

EVAL             evl/flags  Execute some Perl code.
                 2

# Modifiers

MINMOD           no         Next operator is not greedy.
LOGICAL          no         Next opcode should set the flag only.

# This is not used yet
RENUM            off 1 1    Group with independently numbered parens.

# Regex Subroutines
GOSUB            num/ofs 2  recurse to paren arg1 at (signed) ofs arg2

# Special conditionals
GROUPPN          no-sv 1    Whether the group matched.
INSUBP           num 1      Whether we are in a specific recurse.
DEFINEP          none 1     Never execute directly.

# Backtracking Verbs
ENDLIKE          none       Used only for the type field of verbs
OPFAIL           no-sv 1    Same as (?!), but with verb arg
ACCEPT           no-sv/num  Accepts the current matched string, with
                 2          verbar

# Verbs With Arguments
VERB             no-sv 1    Used only for the type field of verbs
PRUNE            no-sv 1    Pattern fails at this startpoint if no-
                            backtracking through this
MARKPOINT        no-sv 1    Push the current location for rollback by
                            cut.
SKIP             no-sv 1    On failure skip forward (to the mark)
                            before retrying
COMMIT           no-sv 1    Pattern fails outright if backtracking
                            through this
CUTGROUP         no-sv 1    On failure go to the next alternation in
                            the group

# Control what to keep in $&.
KEEPS            no         $& begins here.

# Validate that lookbehind IFMATCH and UNLESSM end at the right place
LOOKBEHIND_END   no         Return from lookbehind (IFMATCH/UNLESSM)
                            and validate position

# SPECIAL  REGOPS

# This is not really a node, but an optimized away piece of a "long"
# node.  To simplify debugging output, we mark it as if it were a node
OPTIMIZED        off        Placeholder for dump.

# Special opcode with the property that no opcode in a compiled program
# will ever be of this type. Thus it can be used as a flag value that
# no other opcode has been seen. END is used similarly, in that an END
# node cant be optimized. So END implies "unoptimizable" and PSEUDO
# mean "not seen anything to optimize yet".
PSEUDO           off        Pseudo opcode for internal use.

REGEX_SET        depth p    Regex set, temporary node used in pre-
                            optimization compilation

在优化器信息之后是偏移量/长度表的转储,这里跨多行拆分

Offsets: [45]
	1[4] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 5[1]
	0[0] 12[1] 0[0] 6[1] 0[0] 7[1] 0[0] 9[1] 8[1] 0[0] 10[1] 0[0]
	11[1] 0[0] 12[0] 12[0] 13[1] 0[0] 14[4] 0[0] 0[0] 0[0] 0[0]
	0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 18[1] 0[0] 19[1] 20[0]  

这里的第一行表示偏移量/长度表包含 45 个条目。每个条目都是一对整数,用offset[length]表示。条目从 1 开始编号,因此这里条目 #1 是1[4],条目 #12 是5[1]1[4]表示标记为1:1: ANYOF[bc])的节点从正则表达式的预编译形式中的字符位置 1 开始,长度为 4 个字符。位置 12 中的5[1]表示标记为12:12: EXACT <d>)的节点从正则表达式的预编译形式中的字符位置 5 开始,长度为 1 个字符。位置 14 中的12[1]表示标记为14:14: CURLYX[0] {1,32767})的节点从正则表达式的预编译形式中的字符位置 12 开始,长度为 1 个字符——也就是说,它对应于预编译正则表达式中的+符号。

0[0] 项目表示没有对应的节点。

运行时输出

首先,在进行匹配时,即使启用了调试,也可能不会获得任何运行时输出。这意味着正则表达式引擎从未被调用,因此所有工作都是由优化器完成的。

如果正则表达式引擎被调用,输出可能如下所示

  Matching '[bc]d(ef*g)+h[ij]k$' against 'abcdefg__gh__'
    Setting an EVAL scope, savestack=3
     2 <ab> <cdefg__gh_>    |  1: ANYOF
     3 <abc> <defg__gh_>    | 11: EXACT <d>
     4 <abcd> <efg__gh_>    | 13: CURLYX {1,32767}
     4 <abcd> <efg__gh_>    | 26:   WHILEM
				0 out of 1..32767  cc=effff31c
     4 <abcd> <efg__gh_>    | 15:     OPEN1
     4 <abcd> <efg__gh_>    | 17:     EXACT <e>
     5 <abcde> <fg__gh_>    | 19:     STAR
			     EXACT <f> can match 1 times out of 32767...
    Setting an EVAL scope, savestack=3
     6 <bcdef> <g__gh__>    | 22:       EXACT <g>
     7 <bcdefg> <__gh__>    | 24:       CLOSE1
     7 <bcdefg> <__gh__>    | 26:       WHILEM
				    1 out of 1..32767  cc=effff31c
    Setting an EVAL scope, savestack=12
     7 <bcdefg> <__gh__>    | 15:         OPEN1
     7 <bcdefg> <__gh__>    | 17:         EXACT <e>
       restoring \1 to 4(4)..7
				    failed, try continuation...
     7 <bcdefg> <__gh__>    | 27:         NOTHING
     7 <bcdefg> <__gh__>    | 28:         EXACT <h>
				    failed...
				failed...

输出中最重要信息是关于当前正在针对目标字符串测试的已编译正则表达式的特定节点。这些行的格式为

字符串偏移量 <前字符串> <后字符串> |ID: 类型

类型信息相对于回溯级别缩进。其他附带信息会穿插在其中。

调试 Perl 内存使用情况

Perl 在内存使用方面是一个挥霍无度的浪费者。有一种说法是,要估计 Perl 的内存使用量,假设一个合理的内存分配算法,将该估计值乘以 10,虽然你可能仍然会错过目标,但至少你不会那么惊讶。这并不完全正确,但可以让你很好地了解发生了什么。

假设一个整数不能占用少于 20 字节的内存,一个浮点数不能占用少于 24 字节的内存,一个字符串不能占用少于 32 字节的内存(所有这些示例都假设 32 位架构,结果在 64 位架构上会更糟糕)。如果一个变量以三种不同方式中的两种方式访问(需要一个整数、一个浮点数或一个字符串),内存占用可能会增加另外 20 字节。一个糟糕的 malloc(3) 实现会大幅度地夸大这些数字。

另一方面,像这样的声明

sub foo;

可能会占用高达 500 字节的内存,具体取决于你运行的 Perl 版本。

关于源代码到编译代码膨胀的轶事估计表明,膨胀率为 8 倍。这意味着,合理(通常有注释、正确缩进等)代码的编译形式在内存中占用的空间大约是磁盘上代码的 8 倍。

-DL 命令行开关在 Perl 5.6.0 左右已经过时(它只有在 Perl 使用 -DDEBUGGING 构建时才可用)。该开关用于跟踪 Perl 的内存分配和可能的内存泄漏。如今,建议使用 Purifyvalgrind 等内存调试工具。另请参阅 "PERL_MEM_LOG" in perlhacktips.

要找出 Perl 数据结构使用了多少内存,一种方法是从 CPAN 安装 Devel::Size 模块:它会告诉你存储特定数据结构所需的最小字节数。请注意 size() 和 total_size() 之间的区别。

如果 Perl 使用 Perl 的 malloc 编译,你可以通过设置 $ENV{PERL_DEBUG_MSTATS} 来分析 Perl 内存使用情况。

使用 $ENV{PERL_DEBUG_MSTATS}

如果您的 Perl 使用 Perl 的 malloc() 并且在编译时启用了必要的开关(这是默认设置),那么在编译您的代码时,当 $ENV{PERL_DEBUG_MSTATS} > 1 时,它将打印内存使用统计信息,并在程序终止之前,当 $ENV{PERL_DEBUG_MSTATS} >= 1 时,它也会打印内存使用统计信息。报告格式类似于以下示例

 $ PERL_DEBUG_MSTATS=2 perl -e "require Carp"
 Memory allocation statistics after compilation: (buckets 4(4)..8188(8192)
    14216 free:   130   117    28     7     9   0   2     2   1 0 0
		437    61    36     0     5
    60924 used:   125   137   161    55     7   8   6    16   2 0 1
		 74   109   304    84    20
 Total sbrk(): 77824/21:119. Odd ends: pad+heads+chain+tail: 0+636+0+2048.
 Memory allocation statistics after execution:   (buckets 4(4)..8188(8192)
    30888 free:   245    78    85    13     6   2   1     3   2 0 1
		315   162    39    42    11
   175816 used:   265   176  1112   111    26  22  11    27   2 1 1
		196   178  1066   798    39
 Total sbrk(): 215040/47:145. Odd ends: pad+heads+chain+tail: 0+2192+0+6144.

可以使用标准 Devel::Peek 模块中的 mstat() 函数在执行过程中的任意点请求此类统计信息。

以下是该格式的一些解释

buckets SMALLEST(APPROX)..GREATEST(APPROX)

Perl 的 malloc() 使用桶式分配。每个请求都会向上舍入到最接近的桶大小,然后从该大小的桶池中获取一个桶。

上面的行描述了当前正在使用的桶的范围。每个桶都有两个大小:内存占用和可以放入该桶的用户数据的最大大小。假设在上面的示例中,最小的桶大小为 4。最大的桶的可使用大小为 8188,内存占用为 8192。

在为调试而构建的 Perl 中,一些桶的可使用大小可能为负。这意味着这些桶无法(也不会)使用。对于较大的桶,内存占用可能比 2 的幂大一页。如果是这样,则相应的 2 的幂将打印在上面的 APPROX 字段中。

Free/Used

紧随其后的 1 或 2 行数字对应于 SMALLESTGREATEST 之间每个大小的桶的数量。在第一行中,桶的大小(内存占用)为 2 的幂,或者可能比 2 的幂大一页。在第二行(如果存在)中,桶的内存占用介于两个“上面”的桶的内存占用之间。

例如,假设在前面的示例中,内存占用为

   free:    8     16    32    64    128  256 512 1024 2048 4096 8192
	   4     12    24    48    80

在非 DEBUGGING Perl 中,从 128 开始的桶有 4 字节的开销,因此 8192 长的桶最多可以容纳 8188 字节的分配。

Total sbrk(): SBRKed/SBRKs:CONTINUOUS

前两个字段给出 Perl sbrk(2) 的总内存量(ess-broken?:-) 和使用的 sbrk(2) 的数量。第三个数字是 Perl 对返回的块的连续性的看法。只要这个数字为正,malloc() 就会假设 sbrk(2) 可能提供连续的内存。

外部库分配的内存不计入。

pad: 0

为了保持桶对齐而需要的 sbrk(2) 内存量。

heads: 2192

虽然较大桶的内存开销保留在桶内,但对于较小桶,则保留在单独的区域。此字段给出这些区域的总大小。

chain: 0

malloc() 可能希望将一个较大桶细分为较小桶。如果仅剩下已故桶的一部分未细分,则其余部分将作为链接列表的元素保留。此字段给出这些块的总大小。

tail: 6144

为了最大程度地减少 sbrk(2) 的次数,malloc() 会请求更多内存。此字段给出尚未使用的部分的大小,该部分已使用 sbrk(2) 分配,但从未访问过。

另请参阅

perldebugperl5db.plperlgutsperlrunreDevel::DProf