Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if list element exists in TCL?

Tags:

list

exists

tcl

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 "" }

like image 337
Narek Avatar asked Apr 11 '11 06:04

Narek


2 Answers

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.

like image 148
FriendFX Avatar answered Sep 21 '22 18:09

FriendFX


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!

like image 45
Andrew Rooney Avatar answered Sep 18 '22 18:09

Andrew Rooney