How to check if list element exists in TCL? - list

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.

Why don't you use llength to check the length of your list:
if {[llength $myList] == 6} {
# do something
}
Of course, if you want to check the element at a specific index, then then use lindex to retrieve that element and check that. e.g. if {[lindex $myList 6] == "something"}
Your code using the info exists is not working, because the info exists command checks if a variable exists. So you are basically checking if there is a variable whose name equals the value returned by [lindex $myList 6].

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!

Related

Regular expression is too complex error in tcl

I have not seen this error for a small list. Issue popped up when the list went >10k. Is there any limit on the number of regex patterns in tcl?
puts "#LEVELSHIFTER_TEMPLATES_LIMITSFILE:$perc_limit(levelshifter_templates)"
puts "#length of templates is :[llength $perc_limit(levelshifter_templates)]"
if { [regexp [join $perc_limit(levelshifter_templates) |] $temp] }
#LEVELSHIFTER_TEMPLATES_LIMITSFILE:HDPELT06_LVLDBUF_CAQDP_1 HDPELT06_LVLDBUF_CAQDPNRBY2_1 HDPELT06_LVLDBUF_CAQDP_1....
#length of templates is :13520
ERROR: couldn't compile regular expression pattern: regular expression is too complex
If $temp is a single word and you're really just doing a literal test, you should invert the check. One of the easiest ways might be:
if {$temp in $perc_limit(levelshifter_templates)} {
# ...
}
But if you're doing that a lot (well, more than a small number of times, 3 or 4 say) then building a dictionary for this might be best:
# A one-off cost
foreach key $perc_limit(levelshifter_templates) {
# Value is arbitrary
dict set perc_limit_keys $key 1
}
# This is now very cheap
if {[dict exists $perc_limit_keys $temp]} {
# ...
}
If you've got multiple words in $temp, split and check (using the second technique, which is now definitely worthwhile). This is where having a helper procedure can be a good plan.
proc anyWordIn {inputString keyDictionary} {
foreach word [split $inputString] {
if {[dict exists $keyDictionary $word]} {
return true
}
}
return false
}
if {[anyWordIn $temp $perc_limit_keys]} {
# ...
}
Assuming you want to see if the value in temp is an exact match for one of the elements of the list in perf_limit(levelshifter_templates), here's a few ways that are better than trying to use regular expressions:
Using lsearch`:
# Sort the list after populating it so we can do an efficient binary search
set perf_limit(levelshifter_templates) [lsort $perf_limit(levelshifter_templates)]
# ...
# See if the value in temp exists in the list
if {[lsearch -sorted $perf_limit(levelshifter_templates) $temp] >= 0} {
# ...
}
Storing the elements of the list in a dict (or array if you prefer) ahead of time for an O(1) lookup:
foreach item $perf_limit(levelshifter_templates) {
dict set lookup $item 1
}
# ...
if {[dict exists $lookup $temp]} {
# ...
}
I found a simple workaround for this problem by using a foreach statement to loop over all the regexes in the list instead of joining them and searching, which failed for a super-long list.
foreach pattern $perc_limit(levelshifter_templates) {
if { [regexp $pattern $temp]}
#puts "$fullpath: [is_std_cell_dev $dev]"
puts "##matches: $pattern return 0"
return 0
}
}

How can I order a list by one of its sub elements in TCL

So I have a string that is treated as a list when I split them in the \n and it looks like this:
{aaaa2,bbbb2,cccccc,ddddd\n aaaa3,bbbb4,cccccc,ddddd\n aaaa4,bbbb1,cccccc,ddddd\n aaaa5,bbbb3,cccccc,ddddd}
I need to reorder this list based on B column, in a way that the lesser value comes first and equal values stay together. Meaning it should be something like this:
{aaaa4,bbbb1,cccccc,ddddd\n aaaa2,bbbb2,cccccc,ddddd\n aaaa5,bbbb3,cccccc,ddddd\n aaaa3,bbbb4,cccccc,ddddd}
How can I do it?
If you split each element of your list into a list itself, you can use lsort's -index option:
set lst {aaaa2,bbbb2,cccccc,ddddd
aaaa3,bbbb4,cccccc,ddddd
aaaa4,bbbb1,cccccc,ddddd
aaaa5,bbbb3,cccccc,ddddd}
set lst [lmap item $lst { split $item , }]
set lst [lsort -index 1 $lst]
puts [join [lmap sublist $lst { join $sublist , }] \n]
will output
aaaa4,bbbb1,cccccc,ddddd
aaaa2,bbbb2,cccccc,ddddd
aaaa5,bbbb3,cccccc,ddddd
aaaa3,bbbb4,cccccc,ddddd

How to use foreach inside subst in Tcl (template iteration)?

Does anyone know how if there is a way to include a foreach loop in the subst command, to get a pseudo-template effect?
For example, the following works:
set lim 3
set table sldkfjsl
set sqlpat {
select * from $table limit $lim
}
set sqltext [subst $sqlpat]
But I would like to do something like
set sqlpat {
foreach i {1 2 3} {
select * from ${table}_$i limit $lim;
}
}
set sqltext [subst $sqlpat]
And have it give three separate lines of sql:
select * from sldkfjsl_1 limit 3
select * from sldkfjsl_2 limit 3
select * from sldkfjsl_3 limit 3
Any ideas? Thanks!
(EDIT, my solution which sort of shows how build a strfor command that can be used in a subst template, in my case for passing both SQL and gnuplot code to their respective programs):
proc strfor { nms vals str } {
set outstr ""
foreach $nms $vals {
append outstr [subst $str]
}
return $outstr
}
set foostr1 {select $a from table_$b;\n}
set x [strfor {a b} {A 1 B 2 C 3 D 4} $foostr1]
set foostr2 {
blahsd line 1
blahg line 2
[strfor {a b} {A 1 B 2 C 3 D 4} {
forline1 $a $b
forline2 $b $a
}]
blah later
}
puts [subst $foostr2]
The looping commands in Tcl do not return values, so they are useless in a string which is processed with subst. It is of course possible to write an accumulating looping command as you have done. Another possibility is to use lmap. However, the problem can be solved in an easier way.
set lim 3
set table sldkfjsl
We're going to make a list where every item is an instance of a literal template with variable substitutions. First we create an empty list:
set sqlpats {}
Then we loop for each value in the sequence 1..3. For every iteration we append an instance of the template to the list:
foreach i {1 2 3} {
lappend sqlpats "select * from ${table}_$i limit $lim"
}
(subst isn't necessary here, ordinary variable substitution is sufficient.)
Create a resulting string from the list, with newlines between each item (yep, I was wrong, one more command was needed):
join $sqlpats \n
ETA:
subst is one of those commands which is nice to have, but that I for one almost never use. For most purposes, simpler measures will do. Once in a while though, a convoluted bit of code leaves a string unsubstituted. I pick up subst out of the drawer and zap! That said, the ability to selectively allow or disallow different kinds of substitutions alone makes subst very worthwhile.
Documentation: foreach, join, lappend, lmap, set, subst

Inserting an element in TCL

I am new to TCL scripting. I am trying to insert an element (in a list) in the 5th position. This list has got no values (empty list) initially.
I tried with "linsert" command, but the problem is it cannot insert an element at the position specified by me. Following is the code snippet,
set newlist {}
set newlist [linsert $newlist 5 value_to_be_inserted]
This code doesnot inserts the element in the 5th position, rather it inserts at the beginning in the 0th element. How can i achieve this task.
Any help will be really good for my understanding.
Your list has zero elements. How can you possibly insert at the 5th position when there is no 5th position to insert at? What resulting list are you expecting to have? The only thing I can possibly think of would be to have 5 empty elements followed by your element, which you can achieve simply by saying
set newlist [list {} {} {} {} {} value_to_be_inserted]
If you want the behaviour of e.g. JavaScript, where the list is expanded with empty elements if the index is greater than the length, I think you'll have to make a procedure.
proc expandInsert {list index args} {
set nEmpties [expr {$index - [llength $list]}]
if {$nEmpties > 0} {
lappend list {*}[lrepeat $nEmpties ""]
}
# insert or append args
return $list
}

How to match the variable in switch with contents of a list?

I have a doubt concerning the use of switch in tcl. Mainly, I was wondering if it was possible to make something like:
switch myvar {
list1 {
puts "myvar matches contents of list1"; }
list2 {
puts "myvar matches contents of list2"; }
default {
puts "myvar doesn't match any content of any list"; }
}
In here, list1 and list2 would be either a list or array of strings containing the names of different files.
Is this even possible without making a very detailed regexp search?
Thanks!
You can rewrite it as an if elseif else construct easily, as Brian Fenton already said (and simplify it with the 'in' operator too.
if {$myvar in $list1} {
puts "myvar matches content of list"
} elseif {$myvar in $list2} {
puts "myvar matches content of list2"
} elseif {
puts "myvar doesn't match any content of any list"
}
You could of course wrap up the code and write your own switch version that does what you want, after all, this is Tcl...
proc listswitch {item conditions} {
if {[llength $conditions] % 2} {
return -code error "Conditions must be pairs"
}
set code ""
foreach {cond block} $conditions {
if {$cond eq "default"} {
set code $block
break
} elseif {$item in $cond} {
set code $block
break
}
}
if {$code ne ""} {
uplevel 1 $code
}
}
listswitch 10 {
{10 20 30 50} {
puts "Match in list 1" }
{50 20 90 11} {
puts "Match in list 2"
}
default {
puts "No match"
}
}
You need to worry a little if you want to match filenames literally, or what kind of equality your interested in though. There are some subtle things there, like case insensitive filesystems, different directory separators, absolute vs. relative and even stuff like filesystem encodings which might change the outcome.
Nice question Jason. At first, I thought you wanted a way to compare the contents of two lists. But I think you want to check if the string is a member of the lists. I don't see any easy way to do that with switch, so what I would do is very simply to use lsearch.
if {[lsearch $list1 $myvar ] != -1} {
puts "myvar matches contents of list1"; }
} elseif {[lsearch $list2 $myvar ] != -1} {
puts "myvar matches contents of list2"; }
} else
puts "myvar doesn't match any content of any list"; }
}