I have the following piece of TCL code:

    #wrong format:
    set in_val "12 0 2 0 0 0 1 0 3 698"
    #correct format:
    #set in_val "12 0 1 0 0 0 1 0 3 698"
    set val_ok [regexp {(\d+)\s([01]\s)([01]\s)([01]\s)([01]\s)([01]\s)([01]\s)([01]\s)(\d+)\s(\d+).*} $in_val Var1 Var2 Var3 Var4 Var5 Var6 Var7 Var8 Var9 Var10 Var11]
    if {$val_ok==1} {
       # correct format
       puts "Correct format, continuing..."
       puts "$Var2 $Var3 $Var4 $Var5 $Var6 $Var7 $Var8 $Var9 $Var10 $Var11"
    } else {
       # wrong format
       puts "Wrong format, stimulus [$in_val]"
    }

I want to check if the format described with the regexp function is correct. When the in_val var has the correct format, everything's fine, the if block is exectuted. However, when the format is wrong, instead of entering the else block, I get the following error:

invalid command name "12 0 2 0 0 0 1 0 3 698"
    while executing
"$in_val"
    invoked from within
"if {$val_ok==1} {
# correct format
puts "Correct format, continuing..."
puts "$Var2 $Var3 $Var4 $Var5 $Var6 $Var7 $Var8 $Var9 $Var10 $Var11"

} else {..."
    (file "xxx.tcl" line 3)

I'm using ActiveState ActiveTcl 8.5.11.1 for windows. Any idea about why the error appears when val_ok=0 and the regex doesn't match? Thanks!

J-B

有帮助吗?

解决方案

It's because you're trying to execute $in_val:

puts "Wrong format, stimulus [$in_val]"
                                 ^
                                 |
               you are trying to execute $in_val here

see the square brackets? Removing them would prevent the error:

puts "Wrong format, stimulus : $in_val"

If you still want to print the square brackets then you can backslash escape them:

puts "Wrong format, stimulus \[$in_val\]"
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top