Say I have a TCL list, and I have append some elements to my list. Now I want to check if I have appended 6 or 7 elements.
In order to check if list element exists in the place specified by an index I have used:
if { [info exists [lindex $myList 6]] } {
#if I am here then I have appended 7 elems, otherwise it should be at least 6
}
But seams this does not work. How I should do that? properly? It is OK to check if { [lindex $myList 6]] eq "" }
I found this question because I wanted to check if a list contains a specific item, rather than just checking the list's length.
To see if an element exists within a list, use the lsearch
function:
if {[lsearch -exact $myList 4] >= 0} {
puts "Found 4 in myList!"
}
The lsearch
function returns the index of the first found element or -1
if the given element wasn't found. Through the -exact
, -glob
(which is the default) or -regexp
options, the type of pattern search can be specified.
Another way to check for existence in a list in TCL is to simply use 'in', for instance:
if {"4" in $myList} {
puts "Found 4 in my list"
}
It's slightly cleaner/more readable!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With