在 zsh 中,如何将匿名数组传递给函数?
在 zsh 中,如何将匿名数组传递给函数? 例如寻找类似的东西:
foo() {
echo ${1[2]} '\n';
}
a=(abc def ghi)
foo $a
--> def
或者理想情况下:
foo (abc def ghi)
In zsh, how do I pass anonymous arrays into functions? e.g. looking for something like:
foo() {
echo ${1[2]} '\n';
}
a=(abc def ghi)
foo $a
--> def
Or ideally:
foo (abc def ghi)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以将数组的名称传递给函数,然后函数可以通过将名称解释为变量名称来读取数组。 这种技术对于 bash 中的关联数组等也很有用。 ZSH 使其变得非常容易,因为 (P) 运算符将以所需的方式解释变量。
一个例子可以清楚地说明这一点。 如果您定义此函数:
那么以下代码将执行它:
澄清一下,这是通过对真实数组进行操作来实现的,因此任何空白都会被正确处理:
You can pass the name of the array to the function and then the function can read the array by interpreting the name as a variable name. It is a technique that is also useful for things like associative arrays in bash. ZSH makes it very easy to do, as the (P) operator will interpret the variable in the desired way.
An example will make this clear. If you define this function:
Then the following code will execute it:
And just to clarify, this works by operating on the real array, so any whitespace is handled correctly:
你不能。 函数像任何其他命令一样采用位置参数。
另请注意,您的解决方法不允许任何“数组”元素包含空格。
我能想到的最干净的事情是要求调用者创建一个本地数组,然后从函数中读取它:
我知道 bash 为其补全系统做了类似的杂技,我认为 zsh 也可能如此。 这并不是太不寻常。
You can't. Functions take positional parameters like any other command.
Note also that your workaround doesn't allow any of the "array" elements to contain whitespace.
The cleanest thing I can think of is to require that the caller create a local array, then read it from the function:
I know bash does similar acrobatics for its completion system, and I think zsh might, too. It's not too unusual.
如果您只需要一个数组参数:作为 tail args。
If you only need one array parameter: as tail args.
没有用匿名数组解决......但我尝试了这个东西! 猛击!!...
Not solved with an anonymous array ... But i tried this thing in !! BASH !!...
找到了一个解决方法:
其中parameter2是一串白色分隔的文本,例如'a badkljf odod'
Figured out a workaround:
Where parameter2 is a string of white-separated text, e.g. 'a badkljf odod'