Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

tcl - How can I safely deal with optional parameters

I am writing a proc to create a header in an output file.

Currently it needs to take an optional parameter, which is a possible comment for the header.

I have ended up coding this as a single optional parameter

proc dump_header { test description {comment = ""}}

but would like to know how I can achieve the same using args

proc dump_header { test description args }

It's quite easy to check for args being a single blank parameter ($args == ""), but doesn't cope well if passing multiple parameters - and I need the negative check anyway.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your proc definition is incorrect (you'd get the error message too many fields in argument specifier "comment = """). Should be:

proc dump_header { test description {comment ""}} {
    puts $comment
}

If you want to use args, you could examine the llength of it:

proc dump_header {test desc args} {
    switch -exact [llength $args] {
        0 {puts "no comment"}
        1 {puts "the comment is: $args"}
        default {
            puts "the comment is: [lindex $args 0]"
            puts "the other args are: [lrange $args 1 end]"
        }
    }
}

You might also want to pass name-value pairs in a list:

proc dump_header {test desc options} {
    # following will error if $options is an odd-length list
    array set opts $options

    if {[info exists opts(comment)]} {
        puts "the comment is: $opts(comment)"
    }
    puts "here are all the options given:"
    parray opts
}
dump_header "test" "description" {comment "a comment" arg1 foo arg2 bar}

Some prefer a combination of args and name-value pairs (a la Tk)

proc dump_header {test desc args} {
    # following will error if $args is an odd-length list
    array set opts $args
    if {[info exists opts(-comment)]} {
        puts "the comment is: $opts(-comment)"
    }
    parray opts
}
dump_header "test" "description" -comment "a comment" -arg1 foo -arg2 bar

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...