package for parsing argument in TCL

后端 未结 3 1759
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-14 21:38

Does anyone know a standard package for tcl to easily parse the input arguments ? or a ready proc ? ( I have only 3 flags but something general is preferable ).

3条回答
  •  北海茫月
    2021-01-14 22:12

    Here is a simple, native, no-package argument parser:

    #
    # arg_parse simple argument parser
    # Example `arg_parse {help version} {with-value} {-with-value 123 positional arguments}`
    # will return:
    # `positionals {positional arguments} with-value 123`
    #
    # @param boolean_flags flags which does not requires additional arguments (like help)
    # @param argument_flags flags which requires values (-with-value value)
    # @param args the got command line arguments
    #
    # @return stringified array of parsed arguments
    #
    proc arg_parse { boolean_flags argument_flags args } {
        set argsarr(positionals) {}
    
        for {set i 0} {$i < [llength $args]} {incr i} {
            set arg [lindex $args $i]
            if { [sstartswith $arg "-" ] } {
                set flag [string range $arg 1 end]
                if { [lsearch $boolean_flags $flag] >= 0 } {
                    set argsarr($flag) 1
                } elseif { [lsearch $argument_flags $flag] >= 0 } {
                    incr i
                    set argsarr($flag) [lindex $args $i]
                } else {
                    puts "ERROR: Unknown flag argument: $arg"
                    return
                }
            } else {
                lappend argsarr(positionals) $arg
            }
        }
        return [array get argsarr]
    }
    

    USE argument parser

    #
    # USE argument parser:
    #
    proc my_awesome_proc { args } {
        array set argsarr [arg_parse "help version" "with-value" {*}$args]
        parray argsarr
    }
    

    USE my_awesome_proc :

    % my_awesome_proc -help
    argsarr(help)        = 1
    argsarr(positionals) = 
    % my_awesome_proc -with-value 123
    argsarr(positionals) = 
    argsarr(with-value)  = 123
    % my_awesome_proc -wrong
    ERROR: Unknown flag argument: -wrong
    % my_awesome_proc positional arguments
    argsarr(positionals) = positional arguments
    % 
    

提交回复
热议问题