Skip to content
Tcl Source Code Ticket Change Details
Login

Ticket Change Details

Overview

Artifact ID: bccb4aa0bbcd955a6514dd1692c4f9ae48daf874
Ticket: 1152746fffffffffffffffffffffffffffffffff
TIP #241 -nocase option for [lsearch], [lsort], and [switch]
User & Date: kchansen on 2005-11-15 01:31:45
Changes

  1. icomment:
    Logged In: YES 
    user_id=614439
    
    A Tcl-only approach....
    
    I needed a -nocase option for the switch statement, scanned 
    the tips and found this one.  Here is the approach I took to 
    get effectively the same behavior:
    
    proc CreateCaselessRegExp {Text} {
      set TextUpper [split [string toupper $Text] {}]
      set TextLower [split [string tolower $Text] {}]
    
      foreach Upper $TextUpper Lower $TextLower {
        lappend TextResult "\[$TextUpper$TextLower\]"
        }
    
      set RegExp [join $TextResult {}]
    
      return $RegExp
      };# CreateCaselessRegExp
    
    With this proc, a "switch" with "-exact" and "-nocase" 
    replaces those options with "-regexp", and replaces the exact 
    strings with the result of calling CreateCaselessRegExp.  You 
    must also check to see if the test value is "default" and not 
    change it when it is encountered.
    
    For example:
    
    switch -exact -nocase -- $MyText {
      First {
        ...
        }
      Third {
        ...
        }
      "Another one here" {
        ...
        }
      "Test #9" {
        }
      default {
        }
      }
    
    becomes:
    
    switch -regexp -- $MyText {
      [Ff][Ii][Rr][Ss][Tt] {
        ...
        }
      [Tt][Hh][Ii][Rr][Dd] {
        ...
        }
      "[Aa][Nn][Oo][Tt][Hh][Ee][Rr][  ][Oo][Nn][Ee][  ][Hh][Ee][Rr]
    [Ee]" {
        ...
        }
      "[Tt][Ee][Ss][Tt][  ][##][99]" {
        }
      default {
        }
      }
    
    I actually ended up coding as:
    
    eval {switch -exact -nocase -- $MyText {
      [CreateCaselessRegExp First] {
        ...
        }
      [CreateCaselessRegExp Third] {
        ...
        }
      [CreateCaselessRegExp "Another one here"] {
        ...
        }
      [CreateCaselessRegExp "Test #9"] {
        }
      default {
        }
      }}
    
    As you can see, it could be made a little smarter because all 
    non-alphabet characters end up doubled.  A test could be put 
    in to not create a "one of list" selections for things which are 
    not alphabet, but I figured it was fine for a first cut....  I also 
    liked the fact that I was able to get the case insensitivity with 
    very little extra effort....
    <Karl C. Hansen>
    
    
    
  2. login: "kchansen"
  3. mimetype: "text/plain"
  4. username: "kchansen"