gpt4 book ai didi

zsh - 对带有 Oa 标志的参数扩展结果使用标量或数组赋值时的顺序不同

转载 作者:行者123 更新时间:2023-12-02 07:32:29 25 4
gpt4 key购买 nike

在 zsh 中,如果我执行以下操作

x=(1 2 3)
y=${(Oa)x}
z=(${(Oa)x})

那么 echo $y 将输出 1 2 3,但 echo $z 将输出 3 2 1

显然 y 是一个标量,z 是一个数组,但是为什么对 y 的标量赋值最终没有将“3 2 1”赋值给它?

最佳答案

似乎因为替换规则,'10. 强制加入'优先于'19。 订购'。

这是 zsh 文档:

Rules
Here is a summary of the rules for substitution...
...
10. Forced joining
If the (j) flag is present, or no (j) flag is present but the string is to be split as given by rule 11., and joining did not take place at rule 5., any words in the value are joined together using the given string or the first character of $IFS if none. Note that the (F) flag implicitly supplies a string for joining in this manner.
...
19. Ordering
If the result is still an array and one of the (o) or (O) flags was present, the array is reordered.

--- zshparam(1), rules, zsh parameters

<小时/>

y=${(Oa)x} vs z=(${(Oa)x})

第一种形式是标量赋值,后者是分配数组值。

Description
...
The value of a scalar parameter may also be assigned by writing:
name=value

--- zshparam(1), description, zsh parameters

...

To assign an array value, write one of:
set -A name value ...
name=(value ...)
name=([key]=value ...)

--- zshparam(1), array parameters, zsh parameters

因此,第一种形式产生标量值和后一种数组值:
(以详细形式回显 parameter expansion flag (q) 的值。)

x=(1 2 3)
y=${(Oa)x}
echo ${(qqq)y} ;# look the `y` value in a verbose form with `(qqq)`
#=> "1 2 3" ;# forced joining and resulted scalar value
z=(${(Oa)x})
echo ${(qqq)z}
#=> "3" "2" "1" ;# resulted array value

In scalar assignment, value is expanded as a single string, in which the elements of arrays are joined together

--- zshparam(1), array parameters, zsh parameters

如果表单未使用双引号,则这符合规则 10。

关于zsh - 对带有 Oa 标志的参数扩展结果使用标量或数组赋值时的顺序不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58648505/

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