tcl array question - key with quotes

前端 未结 1 1453
情歌与酒
情歌与酒 2020-12-18 08:35

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
         


        
相关标签:
1条回答
  • 2020-12-18 09:19

    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
    
    0 讨论(0)
提交回复
热议问题