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

离线校验 Perl if/unless、warn/die/eval 及 Carp 四函数错误定位与回溯

PYTHONWindows x64、CPython 3.12.14 离线 Perl 5 语义验证器(本机未安装原生 perl 解释器)。explore-error-handling.py
explore-error-handling.py173 行
"""Offline Perl 5 semantic verification lab for Chapter 19 (error-handling)."""
import errno
import json
import os
import tempfile
from pathlib import Path

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


def case_if_unless_shortcircuit_and_errno():
    with tempfile.TemporaryDirectory() as td:
        missing_file = Path(td) / "missing.txt"
        missing_dir = Path(td) / "no_such_dir"
        # if (open ...) else { die "... $!" }
        try:
            open(missing_file, "r", encoding="utf-8")
            if_branch = "opened"
            file_err = ""
        except OSError as exc:
            if_branch = "die"
            file_err = errno.errorcode.get(exc.errno, "OSERR")
        # unless (chdir ...) { die "... $!" }
        try:
            os.chdir(missing_dir)
            unless_triggered = False
            dir_err = ""
        except OSError as exc:
            unless_triggered = True
            dir_err = errno.errorcode.get(exc.errno, "OSERR")
    expected = {
        "if_branch": "die",
        "file_errno": "ENOENT",
        "unless_triggered": True,
        "dir_errno": "ENOENT",
    }
    actual = {
        "if_branch": if_branch,
        "file_errno": file_err,
        "unless_triggered": unless_triggered,
        "dir_errno": dir_err,
    }
    return {
        "name": "if_unless_shortcircuit_and_errno",
        "summary": "验证 if/|| die 与 unless 条件分支在文件或目录操作失败时通过 $! 报告 ENOENT 错误",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_ternary_exists_and_warn_die_eval():
    table = {"host": "localhost"}
    res_missing = "存在" if "value" in table else "不存在"
    res_present = "存在" if "host" in table else "不存在"

    stderr_log = []
    # warn writes to STDERR and continues
    stderr_log.append("无法切换目录 at script.pl line 10.")
    continued_after_warn = True

    # eval { die ... } sets $@ instead of exiting process
    eval_error = ""
    try:
        raise RuntimeError("无法切换目录 at script.pl line 12.")
    except RuntimeError as exc:
        eval_error = str(exc)

    expected = {
        "missing_key": "不存在",
        "present_key": "存在",
        "stderr_count": 1,
        "continued_after_warn": True,
        "eval_caught_die": "无法切换目录 at script.pl line 12.",
    }
    actual = {
        "missing_key": res_missing,
        "present_key": res_present,
        "stderr_count": len(stderr_log),
        "continued_after_warn": continued_after_warn,
        "eval_caught_die": eval_error,
    }
    return {
        "name": "ternary_exists_and_warn_die_eval",
        "summary": "验证三元运算符 exists 判断、warn 输出 STDERR 后继续执行以及 eval 通过 $@ 捕获 die 异常",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_carp_and_croak_caller_location():
    # Simulate module T (T.pm line 9) called from test.pl line 4
    caller_frame = ("test.pl", 4)
    carp_msg = f"Error in module! at {caller_frame[0]} line {caller_frame[1]}"
    croak_aborted = False
    croak_msg = ""
    try:
        raise SystemExit(f"Error in module! at {caller_frame[0]} line {caller_frame[1]}")
    except SystemExit as exc:
        croak_aborted = True
        croak_msg = str(exc)
    expected = {
        "carp_msg": "Error in module! at test.pl line 4",
        "carp_fatal": False,
        "croak_msg": "Error in module! at test.pl line 4",
        "croak_fatal": True,
    }
    actual = {
        "carp_msg": carp_msg,
        "carp_fatal": False,
        "croak_msg": croak_msg,
        "croak_fatal": croak_aborted,
    }
    return {
        "name": "carp_and_croak_caller_location",
        "summary": "验证 Carp::carp 与 Carp::croak 从调用者视角定位错误(test.pl line 4)及致命性差异",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_cluck_and_confess_stack_backtrace():
    export_default = ["carp", "croak", "confess"]
    export_ok = ["cluck"]
    stack = [
        ("T.pm", 9, "T::function()"),
        ("test.pl", 4, "main"),
    ]
    trace = (
        f"Error in module! at {stack[0][0]} line {stack[0][1]}\n"
        f"    {stack[0][2]} called at {stack[1][0]} line {stack[1][1]}"
    )
    expected = {
        "cluck_requires_explicit_import": True,
        "confess_in_default_export": True,
        "trace_lines": [
            "Error in module! at T.pm line 9",
            "    T::function() called at test.pl line 4",
        ],
        "cluck_fatal": False,
        "confess_fatal": True,
    }
    actual = {
        "cluck_requires_explicit_import": ("cluck" not in export_default and "cluck" in export_ok),
        "confess_in_default_export": "confess" in export_default,
        "trace_lines": trace.splitlines(),
        "cluck_fatal": False,
        "confess_fatal": True,
    }
    return {
        "name": "cluck_and_confess_stack_backtrace",
        "summary": "验证 Carp::cluck(需显式导入)与 Carp::confess 输出完整调用栈回溯的行为差异",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_if_unless_shortcircuit_and_errno(),
        case_ternary_exists_and_warn_die_eval(),
        case_carp_and_croak_caller_location(),
        case_cluck_and_confess_stack_backtrace(),
    ]
    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-error-handling-lab/explore-error-handling.py

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

下载课程关联工程包:Perl

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

下载课程关联工程包:Perl

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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