There are following ways to set a list of variables in a variable.
##Normally we define a list of variables in this format.
set variable {value1 value2 ….. valuen}
set variable “value1 value2 ….. valuen”
##If you have variables in list.
set variable [list value1 value2 …… valuen]
##When you deal with a file where you are looking for a pattern then use below.
set variable [split <item separated by a character> <split_character>]
Let’s understand how we handle the list of variables.
Append an item in a list
If you already have a list of variables and you are looking to add few more items in it at the end, then use below.
Syntax: lappend variable_name variable_value
EG.
set currencies “Rupee Dollar Euro Pound”
lappend currencies Dinar Taka Ruble Yen
puts $currencies
Result: Rupee Dollar Euro Pound Dinar Taka Ruble Yen
Length of a list
IF you are looking to find out the length of the list, then use below command.
Syntax: llength $variable
EG.
set currencies “Rupee Dollar Euro Pound”
puts [llength $currencies]
Result: 4
List item at Index
If you are looking for a variable from list and you know the index of this variable, then use below command.
Syntax: lindex variable index
EG.
set currencies “Rupee Dollar Euro Pound”
puts [lindex $currencies 1]
Result: Dollar
Insert item at an index
If you want to insert an item at any point in the list, then use the index value to place the variable there. If you want to insert the new variable value, then you can use lappend command.
Syntax: linsert variable_name index variable_vlaues
EG.
set currencies “Rupee Dollar Euro Pound”
set currencies [linsert $currencies 3 Yen]
puts $currencies
Result: Rupee Dollar Euro Yen Pound
Replace item at an index
If you want to replace any item with the index, then use below command.
Syntax: lreplace variable_name index variable_value
EG.
set currencies “Rupee Dollar Euro Yen Pound”
set currencies [lreplace $currencies 3 Ruble]
Result: Rupee Dollar Euro Ruble Pound
Set an item at an index
If one wants to insert a variable in any index place use below command. This command is similar to lreplace.
Syntax: lset variable_name index variable_value
EG.
set currencies “Rupee Dollar Euro Yen Pound”
lset currencies 3 Ruble
puts $currencies
Result: Rupee Dollar Euro Ruble Pound
Assign the variable values in list to variables
If one wants to set all the variable values from list to a bunch of variables, then use below command.
Syntax: lassign variable_name variable1 variable2 variable3 …. variablen
EG.
set currencies “Rupee Dollar Euro Pound”
lassign $currencies currency1 currency2 currency3 currency4
puts “$curency1 $currency2 $currency3 $currency4”
Result: Rupee Dollar Euro Pound
Sorting a list
If there are variable values present and we want to sort them, then use below command.
Syntax: lsort $variable_name
EG.
set currencies “Rupee Dollar Euro Pound”
lsort $currencies
Result: Dollar Euro Pound Rupee