如何在tcl中以统一的方式显示输出

dev*_*eva 4 tcl

我对format命令有疑问.我的输出是一种群集,不像下面那样不均匀

    24-04-2011    16:07  <DIR>  Administrator 
    15-05-2011 16:05 <DIR> confuser 
    01-02-2011   20:57  <DIR>  Public 
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能以正确和统一的方式显示输出.一切都在同一列的开头.像这样 :

是的我用这个命令puts [format {%-s %-4s %-8s} $user\t $date\t $time]给我输出如下:

Administrator 15-05-2011 16:05 
confuser 01-02-2011 20:57 
Public 29-01-2011 19:28 
TechM 30-04-2011 09:47
Run Code Online (Sandbox Code Playgroud)

接收的输出是根据第一个字符串中出现的字母数,例如administrator confuser public techm.所以我需要知道的是如何得到一个输出,它没有考虑第一个字符串的长度,并提供一个适当的统一圆柱输出.

Don*_*ows 7

廉价的黑客方法是在输出字符串中使用制表符作为分隔符(" \t"而不是" ”) in your output string. That will work for small amounts of variation, but won't handle wide variations (or small variations around your current terminal/editor's tab width).

To do the job properly, you need to first get a list of all the conceptual lines you want to print out (i.e., the data but not yet formatted). Then you go through each line and work out the width needed for each field, taking the maximum across the whole dataset. With that, you can then configure the format string for format.这是一个例子(对于Tcl 8.5),其中所有内容都被格式化为字符串:

proc printColumnarLines {lines} {
    foreach fields $lines {
        set column 0
        foreach field $fields {
            set w [string length $field]
            if {![info exist width($column)] || $width($column) < $w} {
                set width($column) $w
            }
            incr column
        }
    }
    foreach fields $lines {
        set column 0
        foreach field $fields {
            puts -nonewline [format "%-*s " $width($column) $field]
            incr column
        }
        puts ""; # Just the newline please
    }
}
Run Code Online (Sandbox Code Playgroud)

位置*的格式字符串表示采用另一个指定该字段宽度的参数.不过我错过了,我并不感到惊讶; 格式字符串实际上是一种非常密集的微语言,很容易跳过一个重要的位.(对于使用它们的所有其他语言也是如此;很少有人知道你可以用它们做的所有事情.)

你可以使用固定的字段集来做更多智能的事情,其他的%序列也支持它*.请注意,我通常必须尝试获得我想要的东西(特别是浮点数...)