如何拆分变量并将其结果存储在tcl

时间:2016-06-22 07:21:24

标签: tcl

我在变量中有以下数据:

Timestamp,6/22/2016 2:25:00 AM
mos,4.16
jitter,19.22

我想拆分此变量并将结果存储在3个不同的变量中,如下所示:

Timestamp = 6/22/2016 2:25:00 AM
mos = 4.16
jitter = 19.22 

有没有办法做到这一点?

3 个答案:

答案 0 :(得分:4)

% set input "Timestamp,6/22/2016 2:25:00 AM
mos,4.16
jitter,19.22"
Timestamp,6/22/2016 2:25:00 AM
mos,4.16
jitter,19.22
% set lines [split $input \n]
{Timestamp,6/22/2016 2:25:00 AM} mos,4.16 jitter,19.22
% foreach line $lines {
    lassign [split $line ,] varname value
    set $varname $value
    set result($varname) $value
}
% set Timestamp
6/22/2016 2:25:00 AM
% set mos
4.16
% set jitter
19.22
% parray result
result(Timestamp) = 6/22/2016 2:25:00 AM
result(jitter)    = 19.22
result(mos)       = 4.16

答案 1 :(得分:2)

为了完整性,有关Dinesh解决方案的两个变体:

foreach item [split $input \n] {
    set value [lassign [regsub , $item { }] name]
    set result($name) $value
}

这里的主要区别在于它只对第一个逗号进行了(准)拆分(结果字符串被视为一个常规的以空格分隔的列表,可能有两个以上的元素,因此lassign的替代调用)。

foreach {- name value} [regexp -line -inline -all {^([^,]+),(.*)$} $input] {
    set result($name) $value
}

这个展示了Donal建议的正则表达式分裂。

文档:foreachlassignSyntax of Tcl regular expressionsregexpregsubsetsplit

答案 2 :(得分:-3)

     Timestamp,6/22/2016 2:25:00 AM
    mos,4.16
    jitter,19.22
    You can spit with (,) and you find an array . 
    then you retrieve the value of Index wise .
    As :- if variable name is var="6/22/2016 2:25:00 AM,4.16,19.22";  
    then   String[] val= var.split(",");
    val[0] = 6/22/2016 2:25:00 AM ;
    val[1] = 4.16;
    val[2] = 19.22;

if your technology is java .