开发者

Mess with functions and associative arrays in ksh93

开发者 https://www.devze.com 2023-03-29 01:00 出处:网络
This is my simple array: typeset -A foo foo[\"first\"]=\"first Value\" foo[\"second\"]=\"second Value\" And I want to do a function that would pick this array, do something and return it back to t

This is my simple array:

typeset -A foo

foo["first"]="first Value"
foo["second"]="second Value"

And I want to do a function that would pick this array, do something and return it back to the script. e.g.

function changeThat {
    eval tmp=\$$1
    tmp["$2"]=$3
    return $tmp
}

I a way could go along in the script and do something like:

foo=changeThat foo "first" "a new first value"

And get a pretty result like

echo ${foo["first"]}
a new first value

Now this doesn't work... Well, I'm aware the syntax is 开发者_开发百科prob not quite right. But I got really lost going through the nuances of evals and scape echo (not to say that I hate it from the bottom of my soul). Besides, my reference is for bash and wouldn't be the first time I miss some trick when it comes to ksh - For instance, I've been so far in ksh88, which does't even have associative arrays, while most people say it should. Turns out that my AIX box does not agree. -_-

thanks!


You can define your function like this:

function changeThat {
  typeset -n ref="$1"
  typeset key="$2"
  typeset value="$3"

  ref["$key"]="$value"
}

typeset -n ref defines the ref variable as a reference to the variable specified by it's value.

When you make this call to the function:

changeThat foo this "mow the lawn"

The variable ref in function changeThat references the variable foo. Using ref is now just like using foo. After calling changeThat

    print ${foo["this"]}

will now output "mow the lawn".

0

精彩评论

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

关注公众号