gpt4 book ai didi

perl - 为什么我不能分配@b || Perl 中的@c 到@a?

转载 作者:行者123 更新时间:2023-12-04 00:53:46 24 4
gpt4 key购买 nike

我想对 @a = @b || @c 进行一些复杂的变体分配,意图采取@b如果非空(因此在 bool 意义上为真),@c否则。文档明确地告诉我我不能。 (事实也是如此!)

The "||", "//" and "&&" operators return the last value evaluated (unlike C's "||" and "&&", which return 0 or 1).

[...]

In particular, this means that you shouldn't use this for selecting between two aggregates for assignment:

@a = @b || @c;              # this is wrong
@a = scalar(@b) || @c; # really meant this
@a = @b ? @b : @c; # this works fine, though


不幸的是,它并没有真正告诉我原因。

我期望会发生的是:
  • @a =是一个数组赋值,在右侧引入列表上下文。
  • @b || @c是右侧,在列表上下文中进行评估。
  • ||是 C 式短路逻辑或。它从左到右评估(如果需要)并传播上下文。
  • @b在列表上下文中评估。如果为真(即非空),则返回。
  • 如果没有,@c也在列表上下文中评估并返回。

  • 显然,我倒数第二句话是错误的。为什么?而且,更重要的是,文档或来源的哪一部分解释了这种行为?

    PS:超出问题的范围,我避免使用三元运算符的文档建议的原因是我的 @b实际上是一个临时的(一个函数调用结果)。

    最佳答案

    逻辑或运算符(“||”)在标量上下文中计算其左侧参数。
    这样做的原因是要弄清楚该论点是否为真。 bool 上下文是标量上下文的一个特例,它强制进入标量上下文。

    来自 perldoc perlop "C-style-Logical-Or"

    Binary "||" performs a short-circuit logical OR operation. That is, if the left operand is true, the right operand is not even evaluated. ...



    来自 perldoc perldata "Scalar values" :

    .... The Boolean context is just a special kind of scalar context where no conversion to a string or a number is ever performed.

    关于perl - 为什么我不能分配@b || Perl 中的@c 到@a?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1357664/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com