In zsh, how do I pass anonymous arrays into functions?

放肆的年华 提交于 2019-12-23 11:46:47

问题


In zsh, how do I pass anonymous arrays into functions? e.g. looking for something like:

foo() {
  echo ${1[2]} '\n';
}

a=(abc def ghi)
foo $a

--> def

Or ideally:

foo (abc def ghi)

回答1:


You can't. Functions take positional parameters like any other command.

Note also that your workaround doesn't allow any of the "array" elements to contain whitespace.

The cleanest thing I can think of is to require that the caller create a local array, then read it from the function:

$ foo() {
   for element in $FOO_ARRAY
   do
       echo "[$element]"
   done
}
$ local FOO_ARRAY; FOO_ARRAY=(foo bar baz quux)
$ foo
[foo]
[bar]
[baz]
[quux]

I know bash does similar acrobatics for its completion system, and I think zsh might, too. It's not too unusual.




回答2:


You can pass the name of the array to the function and then the function can read the array by interpreting the name as a variable name. It is a technique that is also useful for things like associative arrays in bash. ZSH makes it very easy to do, as the (P) operator will interpret the variable in the desired way.

An example will make this clear. If you define this function:

function i_want_array () {
    local array_name=$1

    echo "first array element is: " ${(P)${array_name}[1]}
}

Then the following code will execute it:

% a=(one two three)
% i_want_array "a"
first array element is:  one

And just to clarify, this works by operating on the real array, so any whitespace is handled correctly:

% a=("one two" three)
% i_want_array "a"
first array element is:  one two



回答3:


Not solved with an anonymous array ... But i tried this thing in !! BASH !!...

function join {
  local tmp=($1)

  for (( i=0 ; i<${#tmp[@]}-1 ; i++ )) ; do
    echo -n ${tmp[$i]}$2
  done

  echo ${tmp[$i]}
}

test="abc def ghi"

join "$test" "|"



回答4:


If you only need one array parameter: as tail args.

foo() {
  : if you have any leading non-array args, grab those first:
  local arg1="$1"
  shift
  local arg2="$1"
  shift
  : now $@ is your array arg
  echo $@[2] '\n';
}

a=(abc def ghi)
foo "arg 1" arg2 $a

--> def



回答5:


Figured out a workaround:

foo() {
  local a=$1
  local b=$2

  echo ${(j:---:)${=b}}

  foreach d in ${${=b}}
  do
      echo $d
  done
}

Where parameter2 is a string of white-separated text, e.g. 'a badkljf odod'



来源:https://stackoverflow.com/questions/442012/in-zsh-how-do-i-pass-anonymous-arrays-into-functions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!