Version 0 of Easyargs -Let proceedure switches set themselves

Updated 2005-05-25 22:44:06

I expect that something like this code snippet is already somewhere on the Wiki but I thought it worth a posting as this method allows for cleaner, simpler code.

If a proceedure has a whole range of switches then why waste time parsing the args list with a load of switch options or if.. else.. constructions? Just assume that the switch names themselves have some meaningful description within the scope of the calling proc, strip out the leading "-" and use the remnamt of the string as a variable name.

As the proc documentation should always contain some explanation of the usage of the proceedure, its arguments and switches should be no cause for confusion.

 # -------------------------------------------------------
 # proc: 
 #     easyargs     -just a piece of demo code
 # 
 # args: 
 #     a
 #     b
 # 
 # switches:
 #     -up
 #     -down
 #     -in
 #     -out            
 # 
 # -------------------------------------------------------

 proc easyargs {a b args} {
    # read in args, set values according to switch names
    foreach {opt val} $args {
        set tmp [string trim $opt -] 
        set $tmp $val
    }
    #just to prove that the values are set...
    foreach item {up down in out} {
        puts "$item [set $item]"
    }
 }

 easyargs  red green -up 0 -down 1 -in 0 -out 1