想实现类似dict的功能

Want to achieve a functionality similar to dict

我是TCL新手。我想创建类似 TCL 字典的结构,它有字符串键。我想计算字典中某些类型的出现次数,因此我想在特定索引处更新字典(索引是字符串)。如何实现?

Example: (Logical not with exact tcl syntax)

a['hello'] = 0, a['hi'] = 0
Now if hello is found in the data i am scanning, I would like to update a['hello'] = a['hello'] + 1;

请帮我用语法来实现这个。我使用的tcl版本低于8.5,不支持dict。

dict incr dictionaryVariable key ?increment?

This adds the given increment value (an integer that defaults to 1 if not specified) to the value that the given key maps to in the dictionary value contained in the given variable, writing the resulting dictionary value back to that variable. Non-existent keys are treated as if they map to 0. It is an error to increment a value for an existing key if that value is not an integer. The updated dictionary value is returned.

% set myinfo {firstName Dinesh lastName S age 25}
firstName Dinesh lastName S age 25
% dict incr myinfo age; # This will increase the value of 'age' by 1 which is default
firstName Dinesh lastName S age 26
% dict incr myinfo age 10; # OMG!!!, I'm old already...
firstName Dinesh lastName S age 36
% dict incr myinfo count; # Using non-existing key name will create a key with that name
firstName Dinesh lastName S age 36 count 1
% dict incr myinfo count -1; # Even negative values can be used
firstName Dinesh lastName S age 36 count 0
%

参考: dict incr

我不知道从 8.5 版本开始支持字典。所以我无法在我的脚本中使用 dict 命令。

因此我为此目的使用关联数组 (HashMap)。

示例:

set a(hello)0
set a(hi)    0

set a(hello) [expr $a(hello) + 1]

遍历关联数组:

foreach key [array names a] {
    set count [expr $a($key)]
    puts $count
}