gpt4 book ai didi

arrays - 将数组传递给函数名称冲突

转载 作者:IT王子 更新时间:2023-10-29 00:34:16 25 4
gpt4 key购买 nike

规范

GNU bash,版本 3.1.17(无法升级)


前提

我一直在摆弄数组,我想知道是否有任何方法可以让函数的局部变量与所述函数之外的数组同名。


例子

在下面的示例中,我将尝试显示问题

工作

#!/bin/bash
arr=(1 2 "3 4" 5) # Make global array

myfunc()
{
local args=("${!1}") # Using different name for declaration
echo ${args[@]} # Echo new array


}
myfunc arr[@] # Pass array to function

输出

1 2 3 4 5

不工作

#!/bin/bash

arr=(1 2 "3 4" 5) # Create array

myfunc()
{
local arr=("${!1}") #Not working
echo ${arr[@]} # Not working


}
myfunc arr[@] # Pass array to function

输出

[Blank]

原因

我想将多个数组传递给函数,但不想与传入的数组和本地数组名称发生名称冲突。


尝试过

正如您在上面看到的,我已尝试添加本地功能。我已经扫描了 bash 手册页,但似乎找不到任何其他可以提供我想要的行为的内容

Bash -x 结果

+ arr=(1 2 "3 4" 5)
+ myfunc 'arr[@]'
+ arr=("${!1}")
+ local arr
+ echo

如果需要更多信息,请告诉我。

最佳答案

恭喜您在 3.1 系列的 bash 中遇到了一个错误。

来自Bash ChangeLog在与 bash-3.2-alpha 版本相关的部分中:

This document details the changes between this version, bash-3.2-alpha, and the previous version, bash-3.1-release.

...

f. Fixed two bugs with local array variable creation when shadowing a variable of the same name from a previous context.

关于arrays - 将数组传递给函数名称冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31727410/

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