蓝色天空网mbsky.com · 知识 · 实践 · 创造Perl · 本地阅读预览
教程 / 编程语言 / Perl

Perl 条件语句

系统说明 Perl 布尔真假值判定规则、if/elsif/else、unless/elsif/else、多路分支(given/when)与三元条件运算符 ? : 的用法。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

条件分支原理与 Perl 布尔真假值规则

条件语句根据一个或多个条件表达式求得的真假(True/False)决定后续要执行的代码块。Perl 的布尔判定极为简洁但有关键细节:仅数字 `0`、单字符字符串 `'0'`、空字符串 `""`、空列表 `()` 以及 `undef` 这五种情形被视为假(false),其余所有值(包括负数、`"00"`、空格字符串 `" "` 乃至字符串 `"false"`)均为真(true)。在任意真值前加上逻辑非 `!` 或 `not` 则反转为假。

核心条件语句家族:if、unless 与多路分支

Perl 提供正向条件 `if` 与反向条件 `unless` 两大分支结构(详表见下):`if` 在条件为真时执行,可接零个或多个 `elsif`(注意拼写不是 `elif` 也不是 `else if`)及可选 `else`;`unless` 则在条件为假时执行,同样支持 `elsif` 与 `else`,常用于编写语义更贴近自然语言的防御性判断(不过当分支较复杂时建议改写为 `if` 以减少双重否定带来的阅读负担)。此外,Perl 5.10 起曾引入 `given/when`(早期亦有第三方 `Switch` 模块)实现类似 `switch` 的多路匹配,但因智能匹配 `~~` 长期处于实验并计划废弃状态,现代 Perl 工程更推荐用 `if/elsif` 链或哈希调度表实现多路分派。

三元条件运算符 ? :

对于简单的二选一赋值,可以使用三元条件运算符 `Exp1 ? Exp2 : Exp3;` 替代冗长的 `if...else` 块:先对 `Exp1` 求布尔值,若为真则返回 `Exp2` 的计算结果,否则返回 `Exp3` 的计算结果。例如 `$status = ($favorite > 60) ? "热门网站" : "不是热门网站";` 根据数值阈值一行完成状态判定并赋值给 `$status`。

Perl 条件控制语句类型速查

语句执行语义说明
if 语句由条件表达式与紧随其后的花括号代码块构成,条件为真时执行。
if...else 语句在 if 后附加可选 else 分支,条件为假时转入 else 代码块。
if...elsif...else 语句支持串接多个 elsif 顺序判定多组条件,均不满足时执行最终 else。
unless 语句与 if 相反,仅在条件表达式求值为假时执行其代码块。
unless...else 语句条件为假执行 unless 块,条件为真时转入 else 块。
unless...elsif...else 语句在 unless 后继续接 elsif(注意 elsif 仍为正向真值判定)与最终 else。
switch / given-when 分支依据目标值匹配对应分支;现代 Perl 推荐用 if/elsif 或哈希分派替代实验性 given/when。

离线校验 Perl 五类假值规则、if/elsif/unless 多分支与三元运算符

python · 阅读源码
"""Offline Perl 5 semantic verification lab for Chapter 10 (conditions)."""
import json

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


def perl_truthy(val):
    if val is None or val == 0 or val == "0" or val == "" or val == []:
        return False
    return True


def case_perl_truthiness_rules():
    falsy_inputs = [0, "0", "", [], None]
    truthy_inputs = [1, -1, "00", "false", " ", [0]]
    expected = {
        "all_falsy_are_false": True,
        "all_truthy_are_true": True,
        "not_true_is_false": False,
        "string_00_truthy": True,
    }
    actual = {
        "all_falsy_are_false": all(not perl_truthy(x) for x in falsy_inputs),
        "all_truthy_are_true": all(perl_truthy(x) for x in truthy_inputs),
        "not_true_is_false": not perl_truthy(1),
        "string_00_truthy": perl_truthy("00"),
    }
    return {
        "name": "perl_truthiness_rules",
        "summary": "核对 Perl 仅五类假值(0、'0'、''、空列表()、undef)及 '00'/'false' 为真的判定规则",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_if_elsif_else_chain():
    def classify_score(score):
        if score >= 90:
            return "A"
        elif score >= 60:
            return "B"
        else:
            return "C"

    expected = {"s95": "A", "s75": "B", "s40": "C"}
    actual = {"s95": classify_score(95), "s75": classify_score(75), "s40": classify_score(40)}
    return {
        "name": "if_elsif_else_chain",
        "summary": "验证 if / elsif / else 多分支条件选择(注意 Perl 拼写为 elsif)",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_unless_and_multiway_branch():
    def check_unless(flag, level):
        if not perl_truthy(flag):
            return "unless_body"
        elif level == 2:
            return "elsif_body"
        else:
            return "else_body"

    def dispatch_given(val):
        table = {10: "ten", "perl": "language"}
        return table.get(val, "default")

    expected = {
        "unless_when_false": "unless_body",
        "unless_elsif": "elsif_body",
        "unless_else": "else_body",
        "given_match": "language",
        "given_default": "default",
    }
    actual = {
        "unless_when_false": check_unless(0, 1),
        "unless_elsif": check_unless(1, 2),
        "unless_else": check_unless(1, 3),
        "given_match": dispatch_given("perl"),
        "given_default": dispatch_given(99),
    }
    return {
        "name": "unless_and_multiway_branch",
        "summary": "验证 unless/elsif/else 反向条件语义以及多路分支(given/when 与调度表替代)",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_ternary_operator():
    name = "蓝色天空"
    favorite_low = 10
    favorite_high = 85
    status_low = "热门网站" if favorite_low > 60 else "不是热门网站"
    status_high = "热门网站" if favorite_high > 60 else "不是热门网站"
    expected = {
        "low_output": "蓝色天空 - 不是热门网站",
        "high_output": "蓝色天空 - 热门网站",
    }
    actual = {
        "low_output": f"{name} - {status_low}",
        "high_output": f"{name} - {status_high}",
    }
    return {
        "name": "ternary_operator",
        "summary": "验证三元条件运算符 Exp1 ? Exp2 : Exp3 的两路分支求值",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_perl_truthiness_rules(),
        case_if_elsif_else_chain(),
        case_unless_and_multiway_branch(),
        case_ternary_operator(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 离线脚本确认仅 0/'0'/''/()/undef 为假、'00' 与 'false' 为真,并验证 if/elsif/else、unless 及三元运算符输出正确。
离线校验 Perl 五类假值规则、if/elsif/unless 多分支与三元运算符

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

当前源码 SHA256:e2f3b86ac14913a59bbde64492bfd9db1b558ee3aeee2f7a2e76d90bbc6c431e

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Perl 条件语句实验

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

ZIP SHA256:658485750abb1f984e34af6b23b603f65f93132baa7b4b02711d430cf0490708

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在 Perl 条件判断中,字符串 `'0'`、`'00'` 和 `'false'` 分别会被判定为真还是假?

展开参考解答

`'0'` 为假,因为 Perl 明确规定仅 `0`、`'0'`、`""`、`()` 与 `undef` 为假;`'00'` 和 `'false'` 都是非空且不等于 `'0'` 的字符串,因此在 Perl 中都会被判定为真。

规范与官方依据