‘Invalid bare word "regexp"’ in Tcl script

1.2k Views Asked by At
proc mulval { addr } {

if {regexp {^([2][2-3][0-9])\.+(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-])\.+(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.+(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])$} $addr } {
        puts "Valid IP Multicast Address"
    } else { 
        puts"Invalid IP multicast Address"
    }

}

The above code generates the error invalid bareword "regexp" in tcl .

I wanna know what is the mistake in the word and what is invalid bareword in tcl.How to debug.

2

There are 2 best solutions below

0
On

The mistake is that regexp is written as an unqualified string inside the first argument to if. If you want to have the result of a command as an operand in the condition argument you need to put brackets around it: [regexp ...].

But you shouldn't use regular expressions to validate IP numbers. Dotted decimal is only one of the many possible ways to write an IP number, and trying to sort them out with regular expressions is going to be painful and error-prone.

Use the ip module instead. I'm not an IP expert, but the following should work:

package require ip

proc mulval addr {
    set mc [::ip::prefix 224/4]

    if {[::ip::equal $mc [::ip::prefix $addr/4]]} {
        puts "Valid IP Multicast Address" 
    } else { 
        puts "Invalid IP multicast Address"
    }
}

Documentation for the Tcllib ip module

Documentation: if, package, proc, puts, set

0
On

It doesn't come from your regular expression. It's a Tcl syntax problem. You should write:

if { [ regexp {^([2][2-3][0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])$} $addr ] } {
    puts  "Valid IP Multicast Address" 
} else { 
    puts  "Invalid IP multicast Address"
}

Square brackets indicates that the content must be seen as an executable command.