Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

zsh

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)
like image 609
Aaron Fi Avatar asked Jan 14 '09 05:01

Aaron Fi


People also ask

What is an anonymous array?

An array in Java without any name is known as an anonymous array. It is an array just for creating and using instantly. Using an anonymous array, we can pass an array with user values without the referenced variable. Properties of Anonymous Arrays: We can create an array without a name.

What is anonymous array in C++?

Answer: Anonymous class is a class which has no name given to it. C++ supports this feature. These classes cannot have a constructor but can have a destructor. These classes can neither be passed as arguments to functions nor can be used as return values from functions.

How to make anonymous array in Java?

few examples of creating anonymous array in java: anonymous int array : new int[] { 1, 2, 3, 4}; anonymous String array : new String[] {"one", "two", "three"}; anonymous char array : new char[] {'a', 'b', 'c');


2 Answers

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
like image 126
Matthew Franglen Avatar answered Nov 10 '22 08:11

Matthew Franglen


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.

like image 20
Eevee Avatar answered Nov 10 '22 09:11

Eevee