蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线校验 POD 注释、单双引号插值、Here-Doc 定界规则与标识符命名

PYTHONWindows x64、CPython 3.12.14 离线 Perl 5 语义验证器(本机未安装原生 perl 解释器)。explore-syntax.py
explore-syntax.py157 行
"""Offline Perl 5 semantic verification lab for Chapter 04 (syntax)."""
import json
import re

VERSION = "CPython 3.12.14 offline Perl 5 semantic verifier (perl absent)"


def case_comments_pod_and_whitespace():
    src = (
        "#!/usr/bin/perl\n"
        "# 单行注释\n"
        'print       "Hello, world\\n";\n'
        "=pod 注释\n"
        "多行 POD 注释内容\n"
        "=cut\n"
        'print "Hello\n          world\\n";\n'
    )
    active_lines = []
    in_pod = False
    for line in src.splitlines():
        if re.match(r"^=[A-Za-z]", line):
            in_pod = not line.startswith("=cut")
            continue
        if in_pod:
            continue
        if line.strip().startswith("#") or not line.strip():
            continue
        active_lines.append(line)
    expected = {
        "active_statement_lines": 3,
        "pod_filtered": True,
        "inline_multiline_preserved": True,
    }
    actual = {
        "active_statement_lines": len(active_lines),
        "pod_filtered": all("多行 POD" not in l for l in active_lines),
        "inline_multiline_preserved": "          world\\n" in active_lines[-1],
    }
    return {
        "name": "comments_pod_and_whitespace",
        "summary": "验证 # 单行注释、=pod...=cut 行首块注释以及引号外空白忽略与引号内空白保留规则",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_single_vs_double_quotes_and_escapes():
    env = {"a": "10", "result": '蓝色天空 "mbsky"'}

    def eval_double(raw):
        out = raw
        out = out.replace(r"\"", '"')
        out = out.replace(r"\$", "\x00DOLLAR\x00")
        out = re.sub(r"\$(\w+)", lambda m: env.get(m.group(1), ""), out)
        out = out.replace("\\n", "\n")
        return out.replace("\x00DOLLAR\x00", "$")

    def eval_single(raw):
        return raw

    expected = {
        "double_newline": "Hello, world\n",
        "single_literal": r"Hello, world\n",
        "double_var": "a = 10\n",
        "single_var": r"a = $a\n",
        "escaped_dollar": "$result\n",
        "interpolated_result": '蓝色天空 "mbsky"\n',
    }
    actual = {
        "double_newline": eval_double(r"Hello, world\n"),
        "single_literal": eval_single(r"Hello, world\n"),
        "double_var": eval_double(r"a = $a\n"),
        "single_var": eval_single(r"a = $a\n"),
        "escaped_dollar": eval_double(r"\$result\n"),
        "interpolated_result": eval_double(r"$result\n"),
    }
    return {
        "name": "single_vs_double_quotes_and_escapes",
        "summary": "对比双引号插值/转义与单引号原样字面量语义,验证反斜线转义 $ 与双引号",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_heredoc_interpolation_and_rules():
    a = 10
    body_lines = [
        '这是一个 Here 文档实例,可内嵌 "双引号" 与 \'单引号\'。',
        "例如:a = $a",
    ]
    double_hd = "\n".join(line.replace("$a", str(a)) for line in body_lines) + "\n"
    single_hd = "\n".join(body_lines) + "\n"
    terminator_valid = bool(re.match(r"^EOF$", "EOF"))
    terminator_indented = bool(re.match(r"^EOF$", "  EOF"))
    expected = {
        "double_heredoc_interpolated": True,
        "single_heredoc_raw": True,
        "flush_left_terminator_ok": True,
        "indented_terminator_rejected_classic": True,
    }
    actual = {
        "double_heredoc_interpolated": "a = 10" in double_hd,
        "single_heredoc_raw": "a = $a" in single_hd,
        "flush_left_terminator_ok": terminator_valid,
        "indented_terminator_rejected_classic": not terminator_indented,
    }
    return {
        "name": "heredoc_interpolation_and_rules",
        "summary": "验证 <<" + '"EOF"' + " 与 <<'EOF' 的插值差异及传统 Here-Doc 顶格结束标识规则",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_identifiers_and_filenames():
    ident_re = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
    candidates = ["site_name", "Site_name", "_count2", "2bad", "bad-name"]
    valid_idents = [c for c in candidates if ident_re.match(c)]
    case_distinct = len({"site_name", "Site_name"}) == 2
    script_re = re.compile(r"^[^\s]+\.(pl|PL)$")
    files = ["hello_world.pl", "report.PL", "has space.pl"]
    valid_files = [f for f in files if script_re.match(f)]
    expected = {
        "valid_idents": ["site_name", "Site_name", "_count2"],
        "case_sensitive": True,
        "valid_script_files": ["hello_world.pl", "report.PL"],
    }
    actual = {
        "valid_idents": valid_idents,
        "case_sensitive": case_distinct,
        "valid_script_files": valid_files,
    }
    return {
        "name": "identifiers_and_filenames",
        "summary": "校验 Perl 标识符命名规则、大小写敏感性以及 .pl/.PL 脚本文件命名约定",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_comments_pod_and_whitespace(),
        case_single_vs_double_quotes_and_escapes(),
        case_heredoc_interpolation_and_rules(),
        case_identifiers_and_filenames(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 Perl 5 语义验证器(本机未安装原生 perl 解释器)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Perl 5 语义验证器(本机未安装原生 perl 解释器)。

入口文件:projects/perl-syntax-lab/explore-syntax.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-syntax.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Perl 5 语义验证器(本机未安装原生 perl 解释器)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Perl

课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a2480.zip

下载课程关联工程包:Perl

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2506.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习