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

离线校验 Perl format 值域对齐、续行截断、表头分页与文件句柄切换

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

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


def perl_caret_consume(text: str, width: int) -> tuple[str, str]:
    """Simulate Perl ^<<<< continuation field: word-wrap and consume from text."""
    s = text.lstrip(" ")
    if not s:
        return "", ""
    if len(s) <= width:
        return s, ""
    cut = s.rfind(" ", 0, width + 1)
    if cut > 0:
        return s[:cut], s[cut + 1 :].lstrip(" ")
    return s[:width], s[width:]


def perl_format_field(spec: str, value) -> str:
    """Format a single @ picture field matching Perl format rules."""
    if spec == "@*":
        return str(value)
    width = len(spec)
    if spec.startswith("@") and "#" in spec:
        if "." in spec:
            decimals = len(spec.split(".")[1])
            formatted = f"{float(value):{width}.{decimals}f}"
        else:
            formatted = f"{int(round(float(value))):{width}d}"
        return formatted
    s = str(value)[:width]
    align = spec[1] if len(spec) > 1 else "<"
    if align == "<":
        return s.ljust(width).rstrip(" ")
    if align == ">":
        return s.rjust(width)
    if align == "|":
        pad = width - len(s)
        left = pad // 2
        return (" " * left + s).rstrip(" ")
    return s


def case_format_caret_continuation_wrap():
    text = "alpha bluesky portal"
    first, rem1 = perl_caret_consume(text, 6)
    second, rem2 = perl_caret_consume(rem1, 6)
    third, rem3 = perl_caret_consume(rem2, 5)
    lines = [f"first: {first}", f"second: {second}", f"third: {third}"]
    expected = {
        "lines": ["first: alpha", "second: bluesk", "third: y"],
        "third_truncated_case": "porta",
        "remaining_after_porta": "l",
    }
    # Also verify exact 6/6/5 word split like "google bluesk portal" -> 6, 6, 5
    t2 = "google bluesk portal"
    f1, r1 = perl_caret_consume(t2, 6)
    f2, r2 = perl_caret_consume(r1, 6)
    f3, r3 = perl_caret_consume(r2, 5)
    actual = {
        "lines": lines,
        "third_truncated_case": f3,
        "remaining_after_porta": r3,
    }
    return {
        "name": "format_caret_continuation_wrap",
        "summary": "验证 ^<<<<< 与 ^<<<< 续行文本填充的按词拆分、消耗变量及超宽截断行为",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_format_picture_fields_and_alignment():
    left_v = perl_format_field("@<<<", "Hi")
    right_v = perl_format_field("@>>>", "Hi")
    center_v = perl_format_field("@|||", "Hi")
    num6 = perl_format_field("@##.##", 12.345)
    num7 = perl_format_field("@###.##", 123.4)
    salary = perl_format_field("@#####.##", 2000.00)
    multi = perl_format_field("@*", "line1\nline2")
    expected = {
        "left": "Hi",
        "right": "  Hi",
        "center": " Hi",
        "num6_width": 6,
        "num6": " 12.35",
        "num7_width": 7,
        "num7": " 123.40",
        "salary": "  2000.00",
        "multiline": "line1\nline2",
    }
    actual = {
        "left": left_v,
        "right": right_v,
        "center": center_v,
        "num6_width": len("@##.##"),
        "num6": num6,
        "num7_width": len("@###.##"),
        "num7": num7,
        "salary": salary,
        "multiline": multi,
    }
    return {
        "name": "format_picture_fields_and_alignment",
        "summary": "验证 @<<<、@>>>、@|||、@##.##/@###.##/@#####.## 与 @* 五类值域的宽度与对齐规则",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_format_special_vars_header_and_paging():
    employees = [
        ("Ali", 20, 2000.0),
        ("BlueSky", 30, 2500.0),
        ("Jaffer", 40, 4000.0),
    ]
    lines_per_page = 60
    page_num = 1
    format_name = "EMPLOYEE"
    top_name = "EMPLOYEE_TOP"
    output = []
    # Header rendered once on first write of page 1
    output.extend([
        "===================================",
        f"Name                    Age Page {page_num}",
        "===================================",
    ])
    for name, age, sal in employees:
        row_line = f"{name:<24}{str(age):<3}".rstrip()
        sal_line = perl_format_field("@#####.##", sal)
        output.extend([
            "===================================",
            row_line,
            sal_line,
            "===================================",
        ])
    # Verify ~ blank-line suppression
    raw_stdout_template = ["~ignored when blank", "----------------", "  STDOUT格式", "----------------"]
    rendered_stdout = [ln for ln in raw_stdout_template if not ln.startswith("~")]
    expected = {
        "format_name": "EMPLOYEE",
        "format_top_name": "EMPLOYEE_TOP",
        "page_number": 1,
        "lines_per_page": 60,
        "header_line": "Name                    Age Page 1",
        "first_employee_line": "Ali                     20",
        "first_salary_line": "  2000.00",
        "tilde_suppressed_lines": ["----------------", "  STDOUT格式", "----------------"],
        "perl_installed": shutil.which("perl") is not None,
    }
    actual = {
        "format_name": format_name,
        "format_top_name": top_name,
        "page_number": page_num,
        "lines_per_page": lines_per_page,
        "header_line": output[1],
        "first_employee_line": output[4],
        "first_salary_line": output[5],
        "tilde_suppressed_lines": rendered_stdout,
        "perl_installed": False,
    }
    return {
        "name": "format_special_vars_header_and_paging",
        "summary": "验证 $~、$^、$%、$= 表头分页输出及 ~ 空白行抑制语义",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_format_filehandle_and_select_routing():
    formats = {
        "MYFILE": "=================================\n      输入到文件中\n=================================\n",
        "OTHER": "=================================\n  使用定义的格式输入到文件中\n=================================\n",
        "MYFORMAT": "IGNORED_WHEN_EXPLICIT_HANDLE\n",
    }
    with tempfile.TemporaryDirectory() as td:
        tmp_file = Path(td) / "report.tmp"
        # Step 1: write(MYFILE) uses format named MYFILE even if $~ = MYFORMAT
        default_fh = "STDOUT"
        format_var = "MYFORMAT"
        tmp_file.write_text(formats["MYFILE"], encoding="utf-8")
        # Step 2: select(MYFILE); $~ = "OTHER"; write; then restore STDOUT
        prev_fh = default_fh
        default_fh = "MYFILE"
        format_var = "OTHER"
        with tmp_file.open("a", encoding="utf-8") as f:
            f.write(formats[format_var])
        default_fh = prev_fh
        content = tmp_file.read_text(encoding="utf-8")
        lines = content.splitlines()
    expected = {
        "line_count": 6,
        "first_block_title": "      输入到文件中",
        "second_block_title": "  使用定义的格式输入到文件中",
        "restored_default_fh": "STDOUT",
        "ignored_myformat": "IGNORED_WHEN_EXPLICIT_HANDLE" not in content,
    }
    actual = {
        "line_count": len(lines),
        "first_block_title": lines[1],
        "second_block_title": lines[4],
        "restored_default_fh": default_fh,
        "ignored_myformat": "IGNORED_WHEN_EXPLICIT_HANDLE" not in content,
    }
    return {
        "name": "format_filehandle_and_select_routing",
        "summary": "验证 write(MYFILE) 按句柄同名模板输出与 select(MYFILE) 切换默认句柄配合 $~ 输出追加",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_format_caret_continuation_wrap(),
        case_format_picture_fields_and_alignment(),
        case_format_special_vars_header_and_paging(),
        case_format_filehandle_and_select_routing(),
    ]
    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-formats-lab/explore-formats.py

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

下载课程关联工程包:Perl

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

下载课程关联工程包:Perl

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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