Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: get array of integers?



On Sep 3,  9:59am, sam reckoner wrote:
} 
} I have been doing
} 
} x=$(){1..10}

That's a typo?  You mean

x=( {1..10} )

} Is there a better way?

Probably not, except maybe to skip generating the array at all and use a
"for (( x=1; x <= 10; ++x ))" loop.  Depends on context, of course.
(Make sure "x" is not already defined as an array, or that loop will
not work properly.  Best to explicitly declare "integer x".)

} Also, how can I get a range that steps by 2 instead of by 1 as in
} 
} 1 3 5 7 ...

By being sneaky.

typeset -A x
x=( {1..10} )

Now ${(k)x} is an array of odd numbers, and ${(v)x} is an array of
even numbers.  To get them in ascending order, use ${(nok)x}.  Note
that you have to assign an even number of numbers, that is

x=( {1..9} )

will print an error message and not do the assignment.

Of course this trick doesn't work if you want an array by anything
other than twos.  So a more general approach (if you really want to
avoid that "for" loop) would be

typeset -a x

# Count by 7s from 7 to 70
x=( '$(('{1..10}'*7))' )
x=( ${(e)x} )

# Count by 5s from 1 to 51
x=( '$(('{1..10}'*5+1))' )
x=( 1 ${(e)x} )

Of course you can also get really silly:

# Count by 3s from 3 to 30
setopt extendedglob
typeset -a x
x=( {1..10} )
x=( ${x//(#b)(*)/$(($match*3))} )

That's doing a lot of extra work behind the scenes, though, to match
the pattern, store the backreference, etc.



Messages sorted by: Reverse Date, Date, Thread, Author