Gert Gottschalk
Gert Gottschalk

Reputation: 1716

Tcl : Guaranteed evaluation sequence of a boolean expression?

Let's say I have a conditional Tcl expression that is a boolean combination of steps.

  1. Will the expression always be evaluated left to right (excluding parentheses)?
  2. If the expression becomes true will the rest of the evaluation stop?

I have this piece of code that parses a file and conditionally replaces stuff in the lines.

set fp [ open "file" ]
set data [ read $fp ]
close $fp
foreach line [ split $data \n ] {
    if { $enable_patch && [ regsub {<some_pattern>} $line {<some_other_pattern>} line ]} {
        puts $outfp $line
        <do_some_more_stuff>
    }
}

So my issue here is that unless enable_patch is true, I don't want the line to be modified. Now my test shows that the code is deterministic in Tcl 8.5 on Linux. But I am wondering if this would break under other conditions/ versions/ OSes.

Upvotes: 0

Views: 387

Answers (1)

Jim Lewis
Jim Lewis

Reputation: 45145

Yes, the || and && operators are "short-circuiting" operators in TCL. That means you can rely on them being evaluated left-to-right, and that evaluation will stop as soon as the value of the expression is known.

Upvotes: 2

Related Questions