Search code examples
arrayscshseparator

How can I separate csh array elements with something other than a space?


In a csh script I'm working on I need to have array elements containing spaces, so I need to separate those elements with something other than a space, like a comma. For example, I would like to initialize my array with something like:

set the_array=('Element 1','Element 2','Element 3','Element 4')

Note: I'm well aware of how undesirable it is to work in csh. However, for this project I have no choice ... and yes, I've tried to convince the powers that be that this should be changed, but there is already a large code base that would have to be re-written, so that's been rejected.


Solution

  • There are two ways to initialize an array of strings (that have white spaces in them) in CSH:

    The first way, using commas, uses the brace syntax, or the "glob pattern":

    % set the_array = {'Element 1','Element 2','Element 3','Element 4'}
    % echo $the_array[1]
    Element 1
    

    The second way, without commas, uses parentheses:

    % set the_array = ('Element 1' 'Element 2' 'Element 3' 'Element 4')
    % echo $the_array[1]
    Element 1
    

    This way also allows you to create an array over multiple lines:

    % set the_array = ('Element 1' \
    ? 'Element 2')
    % echo $the_array[1]
    Element 1
    % echo $the_array[2]
    Element 2
    

    To iterate through the_array, you can't simply access each element in a foreach as the following:

    % foreach i ( $the_array )
    foreach? echo $i
    foreach? end
    Element
    1
    Element
    2
    Element
    3
    Element
    4
    

    You need to loop from 1 to N, where N is the length of the array, using seq, shown below:

    % foreach i ( `seq $the_array` )
    foreach? echo $the_array[$i]
    foreach? end
    Element 1
    Element 2
    Element 3
    Element 4
    

    Note that CSH uses 1-based indexing.

    Unfortunately, as you found out, using parentheses with commas will produce the following:

    % set the_array = ('Element 1','Element 2','Element 3','Element 4')
    % echo $the_array[1]
    Element 1,Element 2,Element 3,Element 4
    

    Sources