TCL subst or eval command is not working in my case ..

前端 未结 3 2103
醉酒成梦
醉酒成梦 2021-01-26 10:30
subst or eval command is not working in my case .. 

% proc sum {a b} {
    return [expr $a+$b]
}
%
% set a 1
1
% set b 2
2
% sum $a $b
3

%
% sum {$a} {$b}
can\'t use n         


        
3条回答
  •  不要未来只要你来
    2021-01-26 10:48

    You don't understand Tcl correctly.

    subst takes a string and substitues all variables in it, right.
    But you pass the result of sum {$a} {$b} into it, which fails.

    So you could either subst each parameter before you call sum:

    sum [subst {$a} {$b}]
    

    Or modify the sum to do the evaluation for you:

    proc sum {a b} {
        uplevel 1 [list expr $a + $b]
    }
    

    expr does an own round of evaluation, this is why you usually pass a litteral string (enclosed with {}) to it, but in this case we actually use this fact. uplevel executes the command in the context of the caller.

    If you call a command, Tcl will replace the variables before the actuall call is made, so maybe this snippet could help you to understand Tcl a little bit better:

    set a pu
    set b ts
    $a$b "Hello World!"
    

提交回复
热议问题