Getting a list element
As we can now determine the number of elements contained within a list, it is time to retrieve one or more of those elements. To accomplish this, Tcl provides the lrange
command. The syntax is as follows:
lrange list first last
How to do it…
In the following example, we will pass a list to the lrange
command to retrieve the elements contained with the indices provided. Return values from the commands are provided for clarity. Enter the following command:
% lrange {John Mary Bill Fred Tom Sally} 0 1 John Mary
How it works…
The lrange
command accepts a valid Tcl list and returns a new list consisting of the elements referenced in the index values provided in first
and last
last inclusive. If the index contained in first
is less than 0, it is treated as 0. If the index contained in last
is greater than or equal to the number of elements, it is treated as if it were end
, as described previously, where indexes are concerned.