Davosaur
Davosaur

Reputation: 65

Can compound variables be used as function arguments in ksh?

How do you use compound variables in non-trivial situations like function parameters in ksh? Is it possible? How would you make the commented lines in this example code work?

func(){
    print ${1.a}  #reference argument object members. output would be 'dog'
    newObject=$1  #assign compound variable to new variable
    echo ${newObject.a} ${newObject.b}  #output would be 'dog cat'
}
obj=( a=dog b=cat )
func $obj  #call function with compound argument

Clarification: This is not an associative array in bash. It is a compound variable (like an object) in ksh.

Upvotes: 1

Views: 181

Answers (1)

markp-fuso
markp-fuso

Reputation: 35246

Had to dust off the ksh cobwebs ...

There are a couple steps:

  • pass the variable name (not the value) to the function
  • in the function use typeset -n (or nameref) to allow the function to reference the array by a 'local' name

One example would look like:

$ func(){
    typeset -n newObject=${1}
    echo ".${newObject.a}.${newObject.b}."
}

$ obj=( a=dog b=cat )
$ func obj
.dog.cat

Here's a ksh fiddle

Upvotes: 2

Related Questions