12.3 Array Assignment

12.3.1 Synopsis

array_name [ ] = {element_1, element_2, ... element_n};
array_name [ ] = expression;

12.3.2 Description

With the former syntax, if no array called array_name exists it is created and elements element_1 to element_n are stored within. If an array with the same name already exists, its elements are deleted and replaced by new ones. Elements can be any valid expression.

With the latter syntax expression is evaluated and its result assigned to array_name. Please note that the evaluated expression must be an array because of the braces after array_name. Cows will raise an error if you try to assign a scalar value to an array variable.

The following statement:

array_name = expression;

is more flexible since expression can also be a scalar value but can lead to errors if the context of your script requires array_name to be an array variable.

12.3.3 Example

Let's define an array:

cows_array [ ] = { "Behind every beautiful fur,\n",
                   "there is a story.\n",
                   "It is a bloody, barbaric story.\n",
                   "-- Mary Tyler Moore\n" };

An array called cows_array, consisting of four strings is created. These are the elements and their values:

cows_array [0]

Behind every beautiful fur,

cows_array [1]

there is a story.

cows_array [2]

It is a bloody, barbaric story.

cows_array [3]

- Mary Tyler Moore

Now, suppose to type the following lines within the same script:

author = "-- Charlize Theron";
cows_array [ ] = { "We don't live the lives of Eskimos.\n",
                   "We don't need to kill animals for fashion.\n",
                   author };

Cows_array has been replaced by the new definition; this time one of the elements has been initialized with a variable. These are the new values:

cows_array [0]

We don't live the lives of Eskimos.

cows_array [1]

We don't need to kill animals for fashion.

cows_array [2]

- Charlize Theron

This manual can be downloaded from http://www.g-cows.org/.