2

In other dynamic typed, interpeted languages (Ruby, PERL...), one can defined a key in a hash as an inline of a function call. For example (in Ruby:

a[ foo(1) ] = bar

I have tried to do the same in Tcl 8.4, but failed, see tclsh log below:

% proc add1 { x } { expr {$x + 1 } }
% array set p {}
% set p( [add1 1]) 0
wrong # args: should be "set varName ?newValue?"

Needsless to say, that I assign a variable to the output of of add1 1, and use the variable value, it does work:

% set a [add1 1]
2
% set p($a) 0
0

It is a style issue, no doubt, but I like inlining functions, and not using intermediate vriables. Any suggestions?

2 Answers 2

5

It's not really 'pretty' as such, but you can use eval to do something like that:

eval "set p([add1 1]) 0"

First, you give the string "set p([add1 1]) 0" to eval and since it is between quotes, you get a first level of substitution: [add1 1] is evaluated before being passed which means the final string passed to eval is set p(2) 0. eval then evaluates this.


EDIT:

Actually, it works without eval too, your error struck me as strange but didn't pay much attention to a detail. You need to remove the space after the first paren:

set p([add1 1]) 0

Otherwise, set interprets that you're giving the two arguments [add1 1]) and 0 to the variable name p(.

Sign up to request clarification or add additional context in comments.

2 Comments

Yup, that is what I was looking for... Thanks!
If this answer was useful to you, please consider accepting it. See What does it mean when an answer is "accepted"? and How does accepting an answer work?.
0

Here is another way it works, which uses array set:

array set p {}
array set p [list [add1 1] 0]
array set p [list [add1 2] 0]
parray p

Output:

p(2) = 0
p(3) = 0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.