Search code examples
if-statementtclexpr

How to use expr inside if statement?


I have not managed to understand how to embed expr in other constructs. I can easily type

set i {1 2 3}
expr {[llength $i]} #result is 3

However after long research I have not managed to find a way to put that inside if

if {"magic tcl code with expr and llength==3 required here"} {
   puts "length is 3"
}

Solution

  • The first argument to if is an expression, just as the argument to expr is an expression.

    if {[llength $i] == 3} {
        puts "length is 3"
    }
    

    You can indeed put expr inside an expression using [brackets], just as with any command, but there's usually no reason to do so; it just makes everything more verbose.

    if {[ expr {[llength $i]} ] == 3} {
        puts "length is 3"
    }
    

    The exception to the above rule comes when you've got an expression that's somehow dynamic; that's when putting an expr inside an expression makes sense as it allows the outer parts to be bytecode-compiled efficiently.

    # Trivial example to demonstrate
    set myexpression {[llength $i]}
    
    if {[expr $myexpression] == 3} {
        puts "evaluated $myexpression to get three"
    }
    

    That's pretty rare.