Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

matching a pattern

Status
Not open for further replies.

ramsunder

Programmer
Sep 3, 2003
9
DE
Hi,
I can have a list like:

set list1 "0055 888 889 3330"
set list2 "55 888 889 3330"
set list3 "5500 888 889 3330"
set list4 "655 888 889 3330"
set list5 "550 888 889 3330"

and a variable 55, say:
set var 55

I want to write one lserach statement, if I search my variable in above list the results for each corresponding list must be:

lsearch Result for:
list1>> 0
list2>> 0
list3>> -1
list4>> -1
list5>> -1

Can any one please help in writing such lsearch.

Thnaks in advance
 
Hi there,

how about this

Code:
proc listSearch {list value} {
   foreach val $list {
       set val [string trimleft $val 0]
       if {$value == $val} {
          return 0
       }
   }
   return -1
}

Note: the trim left is neccessary to prevent TCL from interpreting numbers with leading zeros (0055) as octal, thus 0055 != 55.
The rest should be quite straightforward.

Greetings,
Tobi
 
Other comments on the potential pitfalls of octal numbers can be found on the Tcl'ers Wiki ( on the page "Tcl and octal numbers,"
Actually, if you're comparing string values that just happen to be numbers, you can do string comparisons instead (as long as "55" should not be equivalent to "055"). Just use the string equal command like this:

Code:
if {[string equal $value $val]} {
    # Do whatever you want when they're equal
}

Also, Tcl 8.4 introduced string equality ([tt]eq[/tt]) and inequality ([tt]ne[/tt]) operators that you can use in any expression. So as of Tcl 8.4, you can get by simply with:

Code:
if {$value eq $val} {
    # Do whatever you want when they're equal
}

- Ken Jones, President, ken@avia-training.com
Avia Training and Consulting, 866-TCL-HELP (866-825-4357) US Toll free
415-643-8692 Voice
415-643-8697 Fax
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top