TCL use a variable to contain list of arguments for format command

Clovertech Forums Cloverleaf TCL use a variable to contain list of arguments for format command

  • Creator
    Topic
  • #118307
    Keith McLeod
    Participant

      Trying to set up list to format using format specifiers.  Looking to have it be dynamic in building the specifiers and the value list to format.

      set listLen 3 – works

      set fmt “%-40.40s %-7.7s [lrepeat $listLen \%\-10\.10s]” – works

      puts [format $fmt “A” “B” “C” “D” “E”] – works

      Since the number of specifiers is 5, is there a way to use a variable for the values like

      set valList {“A” “B” “C” “D” “E”} – works

      puts [format $fmt $valList] – Doesn’t work

      Error: not enough arguments for all format specifiers

      I must be overlooking the obvious.  Any ideas or help is appreciated….

    Viewing 3 reply threads
    • Author
      Replies
      • #118308
        David Barr
        Participant

          The “format” command expects separate arguments, not a list. You can use this syntax:

          puts [format $fmt {*}$valList]

          The “{*}” syntax expands the list into separate arguments to a command.

        • #118309
          Charlie Bursell
          Participant

            Good catch David.  Not a lot of people using the {*} syntax in Cloverleaf but it a very valuable command for your toolbox.  It was added in Tcl 8.5.  See below for usage and examples.

            https://wiki.tcl-lang.org/page/%7B%2A%7D

             

          • #118311
            David Barr
            Participant

              The “{*}” syntax explains how to write this the way you originally proposed, but I thought of another way to do this that may be simpler. Instead of dynamically building the format string and using that to generate the output string, it may be easier to dynamically generate the output string. Something like this:

              set v1 A
              set v2 B
              set valList { C D E }
              set outVal [format “%-40.40s %-7.7s ” $v1 $v2]
              foreach v $valList {
              append outVal [format “%-10.10s” $v]
              }
              puts $outVal

              • This reply was modified 3 years, 11 months ago by David Barr.
              • This reply was modified 3 years, 11 months ago by David Barr.
            • #118314
              Charlie Bursell
              Participant

                Lots of ways in Tcl to do the same things.  For example:

                set fmt “%-40.40s %-7.7s %-10.10s %-10.10s %-10.10s”
                set valList “A  B  C  D  E”
                set cmd {format $fmt}

                foreach var $valList {set cmd [concat $cmd $var]}

                echo [eval $cmd]

                I would still prefer the {*} paradigm.

                The {*} was created because eval can be a pain at times

            Viewing 3 reply threads
            • You must be logged in to reply to this topic.