4

I did in Zsh:

array={geometry, analysis, topology, graph theory, calculus}
echo $array

and then I wanted to add word "math:" to each element like" math:calculus":

while (( i++ < 10)); { echo math:$array[i] }

But it does not work? Why?

  • um, are you sure this is ZSH? That doesn't look like the correct list initialization syntax to me... – jj33 Jun 15 '09 at 19:19

4 Answers4

4

Works fine for me in zsh with the assignment changed from:

array={geometry, analysis, topology, graph theory, calculus}

to

array=(geometry, analysis, topology, graph theory, calculus)

But zsh has tons of options that change its behavior. Maybe the output 'setopt' might help.

Kyle Brandt
  • 83,619
  • 74
  • 305
  • 448
2

Just do:

array=(geometry analysis topology "graph theory" calculus)
print -l math:${^array}

or check RC_EXPAND_PARAM for the ${^var} form.

calandoa
  • 1,285
  • 2
  • 12
  • 14
0

Welp, I'm going to go out on a limb here (because I don't accept that the supporting code is correct) and say that "echo math:$array[i]" is missing a dollar sign and should be "echo math:$array[$i]"

jj33
  • 11,178
  • 1
  • 37
  • 50
  • With mine the i doesn't need the dollar sign. – Kyle Brandt Jun 15 '09 at 19:41
  • well, at least I was right about the initialization being wonky. The ZSH example I looked at used the dollar sigil when referencing the loop variable. – jj33 Jun 15 '09 at 19:44
0

Iterating through an array works better with for because you won't over run the end like your code will (unless you set your limit to the size of the array with ${#array[*]}).

Also, I assume you don't want the commas to be included as part of the strings and you should use parentheses instead of curly braces for your array.

array=(geometry analysis topology "graph theory" calculus)
for i in $array; do echo math:$i; done
Dennis Williamson
  • 62,149
  • 16
  • 116
  • 151