Chang
Chang

Reputation: 1

How to handle empty string when doing an expr in TCL

I have a list

{1 2}
{2 3}
{3 4}
{4 5}
{}
{}
{6 7}

I am trying to do an expression but due the {} empty string, the code below cannot handle it. How should I code it so that, the tool will ignore the empty string in the list?

for {set i 0} {$i < 1} {incr i} {
if {3000 - [lindex $list $i 0] > 2600} {
puts "WARNING"
}}

Output:

WARNING
WARNING
WARNING 

Upvotes: 0

Views: 52

Answers (3)

Donal Fellows
Donal Fellows

Reputation: 137757

Since you are effectively having to deal with empty records, it's probably best to just handle them as a separate step. I prefer to do that by getting the record from the list first:

for {set i 0} {$i < 1} {incr i} {
    set record [lindex $list $i]

    # filter empty
    if {![llength $record]} continue

    # process other records
    if {3000 - [lindex $record 0] > 2600} {
        puts "WARNING"
    }
}

However, if this is the only use of $i, then it might instead be better to write:

foreach record $list {
    # filter empty
    if {![llength $record]} continue

    # process other records
    if {3000 - [lindex $record 0] > 2600} {
        puts "WARNING"
    }
}

Or even:

foreach record $list {
    # filter empty
    if {![llength $record]} continue

    # process other records
    lassign $record x y
    if {3000 - $x > 2600} {
        puts "WARNING"
    }
}

Upvotes: 1

thomas
thomas

Reputation: 210

It would help if you post complete working examples, so we won't need to fill in the gaps ourself. But hoping to get your intentions right, you could do it this way:

set list {1 {}}
set i 1
if {3000 - [expr [lindex $list $i 0] + 0]} {puts done}

Upvotes: 0

amrita yadav
amrita yadav

Reputation: 161

Here is how you can write (if statement) to handle empty string using llength. Modify your loop to skip empty elements:

code:

set list {{1 2} {2 3} {3 4} {4 5} {} {} {6 7}}

for {set i 0} {$i < [llength $list]} {incr i} {
    set sublist [lindex $list $i]
    
    # Skip empty lists
    if {[llength $sublist] == 0} {
        continue
    }

    # Extract first element safely
    set first_element [lindex $sublist 0]

    # Perform the calculation
    if {3000 - $first_element > 2600} {
        puts "WARNING"
    }
}

Upvotes: 0

Related Questions