jay
jay

Reputation: 79

if statement TCL

proc test {} {

set infile [open "infile" r]
set linecount 0

while {[gets $infile line] > 0 {
    incr linecount

    set price [split $line ","]


    if {[reqexp  "Game" $price]} {

       set token [lindex $price end-3]
       set token1 [lindex $price end-2]

    } else {
       if {2 < $linecount < 4} {
       set token [lindex $price end-3]
       set token1 [lindex $price end-2]

       puts "$game"

}
}
}
close $infile

}

I have input file with many lines: I want to be able to puts line 2 to 4 but the if statement I put (if { 0 < $linecount < 2} , does not seem to be working . Do you know how I can ask the script to output for certain lines?

Game a b c
1 2 3 4
3 4 5 6
4 5 6 7
3 4 5 6      

Upvotes: 0

Views: 489

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137767

Like most languages, but not like Python, the binary <= operator will not do what you seem to expect when used like that. It ends up working as if it was written (2 <= $linecount) <= 4, and as the inner term evaluates to either 0 (for false) or 1 (for true), the outer one is always true.

The simplest way to get what you want is to use the tcl::mathop::<= command, which does do what you want with three arguments:

# rest of your code as it was...

if {[tcl::mathop::<= 2 $linecount 4]} {

# rest of your code as it was...

If you're stuck using an old version of Tcl that doesn't have that command (or if you prefer writing code in the following style), write this instead:

if {2 <= $linecount && $linecount <= 4} {

or (if you like more parentheses):

if {(2 <= $linecount) && ($linecount <= 4)} {

Upvotes: 3

Related Questions