Question

I have code in TCL:

set a 1
set b 0
set c "Start"
if { $a == 1 && ($b == 1 || $c == "Start") } {
    puts Works
}

I want to make $c == "Start" to check for case insensitive Start. How can I do it?

Était-ce utile?

La solution

You can use string compare:

string compare ?-nocase? ?-length int? string1 string2

Perform a character-by-character comparison of strings string1 and string2. Returns -1, 0, or 1, depending on whether string1 is lexicographically less than, equal to, or greater than string2. If -length is specified, then only the first length characters are used in the comparison. If -length is negative, it is ignored. If -nocase is specified, then the strings are compared in a case-insensitive manner.

So, if it returns 0, then you have $c exactly equal to String.

set a 1
set b 0
set c "Start"
if { $a == 1 && ($b == 1 || [string compare -nocase $c "Start"] == 0) } {
    puts Works
}

The -nocase switch ensures it uses case insensitive comparison as the documentation mentions.


An alternative could be to make $c to a uniform case and use Start with a uniform case too. For instance, you could convert everything to lowercase:

set a 1
set b 0
set c "Start"
if { $a == 1 && ($b == 1 || [string tolower $c] == "start") } {
    puts Works
}

Or uppercase...

set a 1
set b 0
set c "Start"
if { $a == 1 && ($b == 1 || [string toupper $c] == "START") } {
    puts Works
}

Another alternative could be with regexp, if you don't mind 'exploring' that area.

set a 1
set b 0
set c "Start"
if { $a == 1 && ($b == 1 || [regexp -nocase -- {^Start$} $c]) } {
    puts Works
}

regexp returns 1 for a match and 0 for a non-match. The ^ and $ ensure that the whole Start is matched against the $c variable. Conclusion, if $c is the same as Start, you get 1.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top