"""Offline Perl 5 semantic verification lab for Chapter 20 (special-variables)."""
import json
import os
import re
import sys
VERSION = "CPython 3.12.14 offline Perl 5 semantic verifier (perl absent)"
def case_default_topic_dollar_underscore():
items = ["Alpha", "BlueSky", "Gamma"]
explicit_out = [x for x in items]
implicit_out = [x for x in items] # foreach (...) { print; } uses $_
ords = [ord(s[0]) for s in items]
matched = [s for s in items if re.search(r"Sky", s)]
mapped = [s.upper() for s in items]
expected = {
"explicit_eq_implicit": True,
"explicit_out": ["Alpha", "BlueSky", "Gamma"],
"first_char_ords": [65, 66, 71],
"grep_match": ["BlueSky"],
"map_upper": ["ALPHA", "BLUESKY", "GAMMA"],
}
actual = {
"explicit_eq_implicit": explicit_out == implicit_out,
"explicit_out": explicit_out,
"first_char_ords": ords,
"grep_match": matched,
"map_upper": mapped,
}
return {
"name": "default_topic_dollar_underscore",
"summary": "验证 $_ ($ARG) 在 foreach、无参 print、单目函数、grep/map 与模式匹配中的隐含行为",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_global_scalar_and_english_aliases():
text = "row1\nrow2\nrow3\n"
# $/ = "\n" splits into 3 lines with $. tracking 1..3; undef $/ slurps all
lines = text.splitlines(keepends=True)
nr_final = len(lines)
slurped = text
# $, (OFS), $\ (ORS), $" (LIST_SEPARATOR), $; (SUBSCRIPT_SEPARATOR)
ofs = ","
ors = "\n"
list_sep = " "
subsep = "\034"
print_result = ofs.join(["a", "b", "c"]) + ors
interpolated_arr = list_sep.join(["10", "20", "30"])
pseudo_md_key = subsep.join(["r1", "c2"])
aliases = {
"$_": "$ARG",
"$.": "$NR",
"$/": "$RS",
"$!": "$OS_ERROR or $ERRNO",
"$@": "$EVAL_ERROR",
"$$": "$PROCESS_ID or $PID",
"$0": "$PROGRAM_NAME",
"$^O": "$OSNAME",
}
expected = {
"line_count_dot": 3,
"slurp_len": 15,
"print_with_ofs_ors": "a,b,c\n",
"array_interp": "10 20 30",
"subsep_ord": 28,
"pid_positive": True,
"alias_count": 8,
}
actual = {
"line_count_dot": nr_final,
"slurp_len": len(slurped),
"print_with_ofs_ors": print_result,
"array_interp": interpolated_arr,
"subsep_ord": ord(pseudo_md_key.split("r1")[1][0]),
"pid_positive": os.getpid() > 0,
"alias_count": len(aliases),
}
return {
"name": "global_scalar_and_english_aliases",
"summary": "验证 $.、$/(含 slurp 模式)、$,、$\\、$\"、$;、$$ 等全局标量特殊变量及 use English 别名",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_arrays_hashes_handles_and_constants():
argv = ["--mode", "dry-run"]
inc = ["/usr/local/lib/perl5", "/usr/share/perl5"]
inc_hash = {"Carp.pm": "/usr/share/perl5/Carp.pm"}
sig_keys = ["INT", "TERM", "CHLD"]
script_with_data = "print 1;\n__DATA__\nalpha\nbeta\n"
code_part, data_part = script_with_data.split("__DATA__\n", 1)
data_lines = data_part.splitlines()
constants = {
"__PACKAGE__": "main",
"__FILE__": "demo.pl",
"__LINE__": 42,
}
expected = {
"argv_len": 2,
"inc_first": "/usr/local/lib/perl5",
"inc_loaded": "/usr/share/perl5/Carp.pm",
"env_is_mapping": True,
"sig_has_chld": True,
"data_lines": ["alpha", "beta"],
"default_package": "main",
"std_handles": ["STDIN", "STDOUT", "STDERR"],
}
actual = {
"argv_len": len(argv),
"inc_first": inc[0],
"inc_loaded": inc_hash["Carp.pm"],
"env_is_mapping": isinstance(dict(os.environ), dict),
"sig_has_chld": "CHLD" in sig_keys,
"data_lines": data_lines,
"default_package": constants["__PACKAGE__"],
"std_handles": ["STDIN", "STDOUT", "STDERR"],
}
return {
"name": "arrays_hashes_handles_and_constants",
"summary": "验证 @ARGV/@INC/@F、%INC/%ENV/%SIG、特殊文件句柄(含 DATA)与 __END__/__PACKAGE__ 常量",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_regex_and_filehandle_special_vars():
sample = "Header Revision: 2.4.1 tail"
m = re.search(r"Version: ([^\s]+)|Revision: ([^\s]+)", sample)
prematch = sample[: m.start()]
match = m.group(0)
postmatch = sample[m.end() :]
last_paren_match = next(g for g in reversed(m.groups()) if g is not None)
# $| non-zero => autoflush enabled; 0 => buffered (correcting source typo)
autoflush_when_1 = bool(1)
autoflush_when_0 = bool(0)
expected = {
"reconstructed_eq": True,
"prematch": "Header ",
"match": "Revision: 2.4.1",
"postmatch": " tail",
"last_paren_match": "2.4.1",
"autoflush_when_1": True,
"autoflush_when_0": False,
"default_lines_per_page": 60,
}
actual = {
"reconstructed_eq": (prematch + match + postmatch) == sample,
"prematch": prematch,
"match": match,
"postmatch": postmatch,
"last_paren_match": last_paren_match,
"autoflush_when_1": autoflush_when_1,
"autoflush_when_0": autoflush_when_0,
"default_lines_per_page": 60,
}
return {
"name": "regex_and_filehandle_special_vars",
"summary": "验证 $n/$&/$`/$'/$+ 正则特殊变量及 $| 非零启用自动刷新(纠正源文误写)、$= 默认 60 行语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_default_topic_dollar_underscore(),
case_global_scalar_and_english_aliases(),
case_arrays_hashes_handles_and_constants(),
case_regex_and_filehandle_special_vars(),
]
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-special-variables-lab/explore-special-variables.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-special-variables.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Perl 5 语义验证器(本机未安装原生 perl 解释器)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a2480.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2504.zip