How to use expr inside if statement?

2.3k views Asked by At

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

There are 2 answers

0
Donal Fellows On BEST ANSWER

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.

0
slebetman On

The if command has a built-in expr. Specifically both if and expr expects and expression as the first argument:

if expression ...
expr expression

Therefore, if you want to execute expr {[llength $i]} then just do:

if {[llength $i]} {

}

But to tell you the truth, I don't believe you want to execute

expr {[llength $i]}

I think what you want is to check if the length is 3, therefore what you really want is

expr {[llength $i] == 3}

If that is the case, then the if version would be:

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