Home > Back-end >  How can I pass arrays to functions in zsh similar to using namerefs in bash?
How can I pass arrays to functions in zsh similar to using namerefs in bash?

Time:07-11

I switched my code from bash to zsh for the decimal feature.

I am trying to use namerefs to pass arrays to a function but recieve the error bad option: -n. The code shown below works for bash but not zsh.

An example of what I am doing is below

foo(){
    local -n _array1=$1
    local -n _array2=$2
    echo ${_array2[@]}, ${_array2[@]}
}
main(){
    local array1=(1 1 1 1)
    local array2=(2 2 2 2)
    foo array1 array2
}

main

How can I pass both arrays to the function when using zsh?

CodePudding user response:

In zsh, you have to use the (P) parameter expansion flag instead.

This forces the value of the parameter name to be interpreted as a further parameter name, whose value will be used where appropriate.

Example:

#!/usr/bin/env zsh

demo() {
    printf "%s\n" "${(P)1[@]}"
}

arr=(1 2 3 4 5)
demo arr
  • Related