Perl POD 文档
系统介绍 Perl 嵌入式 POD 标记语言规则、Perl 解释器忽略与 __END__/__DATA__ 行为、三类段落与 13 条核心命令及 pod2html 转换规范。
学完这一章,你能够
- 系统介绍 Perl 嵌入式 POD 标记语言规则、Perl 解释器忽略与 __END__/__DATA__ 行为、三类段落与 13 条核心命令及 pod2html 转换规范。
POD 嵌入规则与 __END__ / __DATA__ 行为对比
Perl 支持在 `.pl` 脚本或 `.pm` 模块源码中直接嵌入 POD(Plain Old Documentation)技术文档。POD 文档段以独占段落的命令(如 `=pod` 或 `=head1`)起始、以 `=cut` 结束恢复 Perl 代码解析,且命令段落前后需用空行与其他内容分隔。Perl 编译运行脚本时会自动跳过 `=head1` 至 `=cut` 之间的全部 POD 内容,仅执行前后正常的 Perl 语句(因此也常被用作多行注释机制)。
此外,还可使用 `__END__` 或 `__DATA__` 标记文件逻辑结束,使所在行之后的文本不再被 Perl 编译器解析执行。若脚本中包含 `while (<DATA>) { print $_; }`,则可把 `__END__` 之后的文档或数据作为只读文本流逐行读出;若脚本未读取 `<DATA>` 句柄,则后续内容会被静默忽略,仅输出 `__END__` 之前的程序结果。
POD 三种段落类型与核心命令集
POD 是一种轻量级标记语言,可经由 `perldoc`、`pod2text`、`pod2man`、`pod2html` 等转换器输出纯文本、Man 手册或 HTML 页面。所有 POD 内容由空行分隔为三大段落类型:(1)**普通段落**(Ordinary Paragraph),左对齐书写,支持 `B<粗体>`、`I<斜体>`、`C<代码>`、`L<链接>` 等内联格式化代码并由渲染器自动重排;(2)**原文段落**(Verbatim Paragraph),以空格或制表符缩进开头,专用于代码示例并保留原始换行与缩进不做重排;(3)**命令段落**(Command Paragraph),以行首 `=` 紧接标识符构成单行指令,核心命令共 13 条:`=pod`、`=head1`..`=head4`、`=over`、`=item`、`=back`、`=begin`、`=end`、`=for`、`=encoding` 与 `=cut`。
使用 pod2html 转换与嵌入原始 HTML
通过命令行工具 `pod2html test.pod > test.html` 可将 POD 文件编译为带目录索引锚点的 HTML 页面。撰写含中文的 POD 文件时,应在顶部使用 `=encoding utf-8` 声明字符编码,并以标准 `=head1 标题` ... `=cut` 组织章节。若需在生成的 HTML 页面中直通输出原始 HTML 片段,应成对使用 `=begin html` 与 `=end html`(注意不要将 `=begin html` 与 `=head1`/`=cut` 混用而遗漏 `=end html`,标准解析器要求每个 `=begin format` 均由对应的 `=end format` 闭合)。
离线校验 Perl POD 词法隔离、__END__/<DATA>、三类段落与 pod2html 转换
展开查看收起
"""Offline Perl 5 semantic verification lab for Chapter 29 (embedded-documentation)."""
import json
import re
VERSION = "CPython 3.12.14 offline Perl 5 POD semantic verifier (perl/pod2html absent)"
def split_perl_and_pod(source: str) -> tuple[list[str], list[str]]:
"""Separate active Perl code lines from embedded POD blocks (=cmd .. =cut)."""
code_lines = []
pod_lines = []
in_pod = False
for line in source.splitlines():
if not in_pod:
if re.match(r"^=[a-zA-Z]", line):
in_pod = True
pod_lines.append(line)
else:
code_lines.append(line)
else:
pod_lines.append(line)
if line.strip() == "=cut":
in_pod = False
return code_lines, pod_lines
def case_pod_parser_cut_and_perl_ignore():
src = (
'#!/usr/bin/perl\n\n'
'print "Hello, World\\n";\n\n'
'=head1 Hello, World 实例\n\n'
'这是一个 Perl 的简单实例。\n\n'
'=cut\n\n'
'print "Hello, BlueSky\\n";\n'
)
code_lines, pod_lines = split_perl_and_pod(src)
prints = [m.group(1) for ln in code_lines for m in [re.search(r'print\s+"([^"]+)\\n";', ln)] if m]
expected = {
"executed_outputs": ["Hello, World", "Hello, BlueSky"],
"pod_ignored_by_perl": True,
"pod_starts_head1": True,
"pod_ends_cut": True,
}
actual = {
"executed_outputs": prints,
"pod_ignored_by_perl": all("简单实例" not in ln for ln in code_lines),
"pod_starts_head1": pod_lines[0].startswith("=head1 "),
"pod_ends_cut": pod_lines[-1].strip() == "=cut",
}
return {
"name": "pod_parser_cut_and_perl_ignore",
"summary": "验证 Perl 词法器忽略 =head1 至 =cut 间 POD 文档并正常执行前后代码",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_end_and_data_filehandle_semantics():
src = (
'print "Hello, World\\n";\n'
'while(<DATA>) { print $_; }\n'
'__END__\n'
'\n'
'=head1 Hello, World 实例\n'
'这是一个 Perl 的简单实例。\n'
'print "Hello, BlueSky\\n";\n'
)
code_part, data_part = src.split("__END__\n", 1)
# Without reading <DATA>, only pre-__END__ print runs
without_data_out = ["Hello, World"]
# With while(<DATA>), lines after __END__ are echoed verbatim as data
with_data_lines = ["Hello, World"] + data_part.splitlines()
expected = {
"without_data_count": 1,
"with_data_first": "Hello, World",
"with_data_contains_pod_line": True,
"trailing_print_not_executed": True,
}
actual = {
"without_data_count": len(without_data_out),
"with_data_first": with_data_lines[0],
"with_data_contains_pod_line": "=head1 Hello, World 实例" in with_data_lines,
"trailing_print_not_executed": 'print "Hello, BlueSky\\n";' not in code_part,
}
return {
"name": "end_and_data_filehandle_semantics",
"summary": "验证 __END__/__DATA__ 终止编译并决定通过 <DATA> 句柄读取或忽略后续文本的行为",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_pod_three_paragraph_types_and_commands():
pod_doc = (
"=encoding utf-8\n\n"
"=pod\n\n"
"=head1 概述\n\n"
"使用 B<粗体> 与 C<代码> 格式化普通段落。\n\n"
" my $x = 42;\n"
" print $x;\n\n"
"=over 4\n\n"
"=item * 第一项\n\n"
"=back\n\n"
"=cut\n"
)
paras = [p for p in re.split(r"\n\s*\n", pod_doc.strip()) if p.strip()]
classified = []
for p in paras:
if p.startswith("="):
classified.append("command")
elif p.startswith((" ", "\t")):
classified.append("verbatim")
else:
classified.append("ordinary")
known_cmds = [
"=pod", "=head1", "=head2", "=head3", "=head4",
"=over", "=item", "=back", "=begin", "=end", "=for", "=encoding", "=cut",
]
expected = {
"paragraph_types": ["command", "command", "command", "ordinary", "verbatim", "command", "command", "command", "command"],
"has_all_three_types": True,
"known_command_count": 13,
}
actual = {
"paragraph_types": classified,
"has_all_three_types": set(classified) == {"command", "ordinary", "verbatim"},
"known_command_count": len(known_cmds),
}
return {
"name": "pod_three_paragraph_types_and_commands",
"summary": "验证 POD 普通段落、原文缩进段落与命令段落三类语法识别及 13 条核心命令清单",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_pod2html_and_begin_end_html_block():
pod_html = (
"=encoding utf-8\n\n"
"=head1 蓝色天空\n\n"
"=begin html\n\n"
"<h1>蓝色天空</h1>\n"
"<p>https://mbsky.example.com</p>\n\n"
"=end html\n\n"
"=cut\n"
)
# Minimal offline pod2html renderer for =head1 and =begin html .. =end html
toc = []
body = []
in_raw_html = False
unclosed_begin = False
for para in re.split(r"\n\s*\n", pod_html.strip()):
if para.startswith("=head1 "):
title = para[7:].strip()
toc.append(f'<li><a href="#{title}">{title}</a></li>')
body.append(f'<h1 id="{title}">{title}</h1>')
elif para.strip() == "=begin html":
in_raw_html = True
elif para.strip() == "=end html":
in_raw_html = False
elif in_raw_html:
body.append(para)
unclosed_begin = in_raw_html
# Also test invalid snippet where =begin html is followed by =cut without =end html
bad_pod = "=begin html\n\n=head1 Title\n\n=cut\n"
bad_unclosed = ("=begin html" in bad_pod) and ("=end html" not in bad_pod)
expected = {
"toc_link_generated": True,
"raw_html_preserved": True,
"valid_begin_closed": False,
"detects_missing_end_html": True,
}
actual = {
"toc_link_generated": '<li><a href="#蓝色天空">蓝色天空</a></li>' in toc,
"raw_html_preserved": any("<h1>蓝色天空</h1>" in b for b in body),
"valid_begin_closed": unclosed_begin,
"detects_missing_end_html": bad_unclosed,
}
return {
"name": "pod2html_and_begin_end_html_block",
"summary": "验证离线 pod2html 索引与标题生成、=begin html/=end html 原文直通及缺配对 =end 检出",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_pod_parser_cut_and_perl_ignore(),
case_end_and_data_filehandle_semantics(),
case_pod_three_paragraph_types_and_commands(),
case_pod2html_and_begin_end_html_block(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`=begin format` 开启的是面向特定格式转换器的透传区域,规范要求与同名 `=end format` 成对闭合;如果遗漏 `=end html` 直接写 `=cut`,标准 POD 校验器(如 `podchecker`)会报语法错误,且中间的 `=head1` 不会被当作常规 POD 标题解析。