how to create tcl proc with hyphen flag arguments

后端 未结 4 792
面向向阳花
面向向阳花 2020-12-10 22:06

Im searching all over the internet , i guess im searching not the right keywords i tried most of them :)

i want to create in tcl/bash a proc with hyphen flags to get

4条回答
  •  孤城傲影
    2020-12-10 22:10

    The usual way to handle this in Tcl is by slurping the values into an array or dictionary and then picking them out of that. It doesn't offer the greatest amount of error checking, but it's so easy to get working.

    proc myExample args {
        # Set the defaults
        array set options {-foo 0 -bar "xyz"}
        # Read in the arguments
        array set options $args
        # Use them
        puts "the foo option is $options(-foo) and the bar option is $options(-bar)"
    }
    
    myExample -bar abc -foo [expr {1+2+3}]
    # the foo option is 6 and the bar option is abc
    

    Doing error checking takes more effort. Here's a simple version

    proc myExample args {
        array set options {-foo 0 -bar "xyz"}
        if {[llength $args] & 1} {
            return -code error "must have even number of arguments in opt/val pairs"
        }
        foreach {opt val} $args {
            if {![info exist options($opt)]} {
                return -code error "unknown option \"$opt\""
            }
            set options($opt) $val
        }
        # As before...
        puts "the foo option is $options(-foo) and the bar option is $options(-bar)"
    }
    
    myExample -bar abc -foo [expr {1+2+3}]
    # the foo option is 6 and the bar option is abc
    
    # And here are the errors it spits out...
    myExample -spregr sgkjfd
    # unknown option "-spregr"
    myExample -foo
    # must have even number of arguments in opt/val pairs
    

提交回复
热议问题