in tcl, can't read a variable when its name is comprised of another variable

后端 未结 3 933
一向
一向 2020-12-19 21:20

Basically, what I\'m doing is

set i 0

set log_$i \"blah blah\"

puts $log_$i;                  # expecting to see \"blah blah\"

this retur

相关标签:
3条回答
  • 2020-12-19 22:03

    Another way:

    % set i 0
    0
    % set log(0) "blah blah"
    blah blah
    % puts $log($i)
    blah blah
    
    0 讨论(0)
  • 2020-12-19 22:04

    The issue you've got is that $-substitution stops when it encounters a $ (and lots of other punctuation too).

    To make what you're doing work, you'd do this to read the variable (using the single-argument form of the set command):

    puts [set log_$i]
    

    That compiles to exactly the sort of bytecode that you'd expect.

    BUT…

    Don't do it that way if you can avoid it.

    Any time you're thinking about constructing variables like that, you're more likely to be in need of using arrays:

    set i 0
    set log($i) "blah blah"
    puts $log($i)
    

    That does work. And if you're really in need of working with a variable whose name is constructed, it's often easier to construct a (typically local) variable alias to it like this:

    set i 0
    upvar 0 log_$i v
    set v "blah blah"
    puts $v
    

    The upvar command is tricky stuff, and allows for all sorts of really powerful techniques. It also makes the local aliases to variables very efficient (though this alias does not include looking up the variable each time; you'll need to rerun upvar if you want the alias to point to something else).

    0 讨论(0)
  • 2020-12-19 22:07

    Another way of doing is

    ==>tclsh

    % set i 0
    
    0
    
    % set log[set i] bb
    
    bb
    
    % puts "[set log[set i]]"
    
    bb
    
    0 讨论(0)
提交回复
热议问题