为什么这个代码在传递给`zsh -n`而不是`zsh`时会抛出错误?

pix*_*tic 3 zsh

我在这个例子中尝试将所有值从一个关联数组复制到另一个关联数组.我正在检查我的代码是否使用了语法错误zsh -n但是这个抛出了一个test:12: bar: assignment to invalid subscript range.

#!/usr/bin/env zsh
typeset -A foo bar
foo=(
    Adama   "Commander"
    Tigh    "Executive Officer"
    Roslin  "President"
)
bar=()

for i in ${(k)foo}; do
    # "rubbish"
    bar[$i]=$foo[$i]
done
Run Code Online (Sandbox Code Playgroud)

如果我取消注释# "rubbish,zsh -n停止抱怨.我的代码还是有问题zsh -n

lol*_*que 5

您可以通过添加调试模式(-x)来查看正在发生的事情

由于non_exec mode(-n)不执行任何操作,因此它不执行,typeset因此bar不是"关联数组",并且赋值无效.

I see that the presence of the "rubbish" line (or other line looking like a command) prevents the program entering in the 'for' loop.

Zsh mailing list: zsh -n doesn't grok associate array indexes? (Jan 2011)

I tried with zsh 4.3.12 and the behaviour is more consistent, with -n the program never enters the 'for' loop.

For a smaller program with no loop:

#!/usr/bin/env zsh
typeset -A bar
bar[test]=testons
echo $bar
Run Code Online (Sandbox Code Playgroud)

zsh 4.3.10 and 4.3.12 will both execute the program the same way, but zsh-4.3.10 -n will wrongly report an error (assignment to invalid subscript range) when zsh-4.3.12 -n will not.

As a conclusion, use zsh 4.3.12 (or newer, i discover that ZSH 5 is available)
News about zsh (Including "news" from 1997!)