Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tcl array question - key with quotes

Tags:

arrays

tcl

this surprised me

>set foo("bar") 12
12
>parray foo
foo("bar") = 12
>set foo(bar) 12
12
>parray foo
foo("bar") = 12
foo(bar)   = 12

it seems that the literal foo is not the same as "foo". And yet

>string length foo
3
>string length "foo"
3

what am I failing to understand

like image 702
pm100 Avatar asked Feb 26 '23 06:02

pm100


1 Answers

The " character is only special to Tcl's parser at the start of a word (or the end of a word that was started by ", of course). In fact, if you'd put spaces in you would have got an error:

% set foo("b a r") 2
wrong # args: should be "set varName ?newValue?"

In the case where you're doing the string length calls, the " is at the start of a word so it is special. If we put an extra leading junk character, we see that the specialness of " goes away:

% string length x"bar"
6

If you're doing something complicated with array indices, I think it's usually easier to put the name of the element in a variable itself, since then it's clearer what's going on (and usually easier to debug too):

set idx "bar"
set foo($idx) 12
like image 155
Donal Fellows Avatar answered Mar 06 '23 09:03

Donal Fellows