开发者

How to manipulate arrays using indirect references in ksh?

I want to do a script of the sort:

#!/usr/bin/ksh93    
typeset -A foo

function fillItUP {
    typeset -A newarr
    newarr["this"]="bar"
    newarr["another"]="tut"

    inputarrayname=$1

    nameref $inputarrayname=newarr
开发者_高级运维}

With an output of the sort:

fillItUP "foo"
echo ${foo["this"]}
bar

I guess its pretty obvious, but what I thought of doing was using a double indirect reference to manipulate the array inside the function and later use it outside. Didn't work :(

Anyone would know a way to achieve this?


Thanks for the explanation . I understand what you are trying to pull off.

Now here is the working code

#!/usr/bin/ksh93
typeset -A foo
foo["this"]="old bar"
foo["another"]="old tut"

function fillItUP {
    nameref newarr=$1
    newarr["this"]="bar"
    newarr["another"]="tut"
    ## nameref newarr=$1


}
fillItUP foo
echo ${foo["this"]}

The whole idea of nameref of typeset -n is to feed a variable from the one scope to the other. In your sample code, you were first allocating a local array to your function fillItUP (NOTE: why local ?? Read this on ...typeset and scope ) and then trying to point the local array to foo. If you want to change foo.. you need to make the local variable point to foo and then change it.

If you uncomment the 'commented nameref' and comment the 'uncommented nameref' You will see that the value of foo is still "old bar". If you execute the code I have added as it is, you will see that the value if foo[this]=bar and not the "old bar"

Hope this helped.

NOTE: You can comment out the initial "old" contents of foo and try it too :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜