Version 2 of Writing case insensitive procedures using unknown

Updated 2010-03-22 13:13:08 by MG

Case Insensitive TCL commands

Some days back I faced an issue with writing case insensitive procedure names. i.e

    proc abc {} {
        puts "Called function abc() .."
    }

This should work with other 7 variants ABC, abC, aBc, aBC, Abc, AbC, aBc.

The solution to this could be to use the unknown function in TCL.

# define the original command name list.

    set orig_cmd_names [list abc]

# Rename the original unknown to unknown_orig

    rename unknown unknown_orig

# Define a customized unknown procedure.

    proc unknown {args} {
        set cmd [lindex $args 0]
        global orig_cmd_names
        foreach oCmd $orig_cmd_names {
            if {[regexp -nocase ^($oCmd)$ $cmd]} {
                # Found the command .. !, now execute it in global scope
                set result [uplevel #0 $oCmd [lrange $args 1 end]]
                return -code ok $result
            }
        }
        # Not found .. :-(, call the base unknown function.
        unknown_orig $args
    }

    %abC
    Called function abc() ..
    %Abc
    Called function abc() ..

MG would recommend using string equal instead of regexp to compare the strings, otherwise you could get inaccurate matches when command names contain chars with special meaning for regexp (proc a..z).