Tcl Arrays
The array is a frequently occurring variable type in programming languages. In Tcl, arrays complement lists by providing additional capabilities when organizing data. Arrays are Tcl variables that have string-based indices (names). Any string value can be used as an array index.
set arrData(this\ is\ a\ test) "HyperWorks";
set indexvar "this is a test";
set arrData($indexvar) "HyperWorks";
set arrData(this,is,a,test) "HyperWorks";
These are all valid array definitions, but note the escape character \ used in the first version to prevent issues with spaces. Unlike brackets, parentheses do not affect how the string is interpreted and will therefore not prevent the white spaces from causing problems. The first two versions are equivalent, and will be evaluated as the same variable in the Tcl environment. The third case is different because the index is not equivalent to the string with spaces. As the index is a string, commas can be used in the indices, though they are not required. The third example illustrates using commas to delimit indices.
- array exists arrayN
- Returns 1 if the array exists, 0 otherwise.
- array get arrayName ?pattern?
- Converts an array of format arrName(index1) containing value1 to a list of format:
- array names arrayName ?mode? ?pattern?
- Returns a list of indices matching pattern. If no pattern is given, returns all indices for the array. Pattern matching is the same as the string match command.
- array set arrayName list
- Converts a list of format:
- array size arrayName
- Returns the number of elements in an array or 0 if the array does not exist or is empty.
- array unset arrayName ?pattern?
- Unsets elements of an array matching pattern, or all elements in the array if no pattern is given. Pattern matching is the same as the string match command.
set curve(color) 5;
set curve(name) "Curve 1";
set curve(display) "on";
puts $curve(color);
5
set name "color";
puts $curve($name);
5
array names curve
name display color
set xcoord 0.0;
set ycoord 1.0;
set zcoord 2.0;
set coords(1,x) $xcoord;
set coords(1,y) $ycoord;
set coords(1,z) $zcoord;
array names env;
Tcl returns a list of environment variables
puts "$env(Path)";
Tcl returns the Path environment variable