Search code examples
switch-statementgetopttclsh

About getopt and switch-statement in tclsh


I have a code.

If input parameter match opt,

then print opt-content

But result is not my expected: How do I solved it?

As following I describe:

I type:

$ tclsh t.tcl -B bb -O oo

I got:

bb
bb
oo
--------
Non
--------
oo
bb
oo
--------
Non
--------

Result seems to goes no match then print default message,

but argument seem to be read(substitute) correct.

FULL CODE


package require cmdline

set parameters {
  {B.arg "" "Build Dir"}
  {O.arg "" "Output Dir"}
}

array set arg [cmdline::getoptions argv ${parameters}]

set requiredParameters {B O } 
foreach iter ${requiredParameters} {
  if {$arg(${iter}) == ""} {
    error "Missing required parameter: -${iter}"
  } else {
    puts $arg(${iter})
    puts $arg(B)
    puts $arg(O)
    puts "--------"
    switch $arg(${iter}) {
      $arg(B) {
        puts $arg(${iter})
      }   
      $arg(O) {
        puts $arg(${iter})
      }   
      default {
        puts "Non"
      }   
    }   
    puts "--------"
  }
}


Solution

  • Finally, I got the solution here

    The braced switch seems to create a new namespace, which isolate outside variable.

    Refer to here:

    Two syntaxes are provided for the pattern and body arguments.
    The first uses a separate argument for each of the patterns and commands;
    this form is convenient if substitutions are desired on some of the patterns or commands.
    The second form places all of the patterns and commands together into a single argument; the argument must have proper list structure, with the elements of the list being the patterns and commands.
    The second form makes it easy to construct multi-line switch commands, since the braces around the whole list make it unnecessary to include a backslash at the end of each line. Since the pattern arguments are in braces in the second form, no command or variable substitutions are performed on them; this makes the behavior of the second form different than the first form in some cases.