在 zsh 中,如何将匿名数组传递给函数?例如寻找类似的东西:
foo() {
echo ${1[2]} '\n';
}
a=(abc def ghi)
foo $a
--> def
或者理想情况下:
foo (abc def ghi)
最佳答案
您可以将数组的名称传递给函数,然后函数可以通过将名称解释为变量名来读取数组。这种技术对于 bash 中的关联数组等内容也很有用。 ZSH 使它变得非常容易,因为 (P) 运算符将以所需的方式解释变量。
一个例子将说明这一点。如果你定义这个函数:
function i_want_array () {
local array_name=$1
echo "first array element is: " ${(P)${array_name}[1]}
}
然后下面的代码将执行它:
% a=(one two three)
% i_want_array "a"
first array element is: one
只是为了澄清,这是通过对真实数组进行操作来工作的,因此可以正确处理任何空格:
% a=("one two" three)
% i_want_array "a"
first array element is: one two
关于zsh - 在 zsh 中,如何将匿名数组传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/442012/