简体   繁体   中英

Mess with functions and associative arrays in ksh93

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. eg

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM