gpt4 book ai didi

arrays - TCL:如何返回数组?

转载 作者:行者123 更新时间:2023-12-01 11:48:32 30 4
gpt4 key购买 nike

请在下面找到一段代码,它传递一个数组,操作数组,但我无法返回新版本的数组。

这是片段:

    proc    get_mroute_active { &multicast }   {
upvar ${&multicast} MULTICAST ;

set group -1 ;
set src -1 ;
set mcast_group_source_id -1 ;
set MULTICAST($mcast_group_source_id,id) $mcast_group_source_id ;
set MULTICAST($mcast_group_source_id,mcast_group) $group ;
set MULTICAST($mcast_group_source_id,mcast_source) $src ;

puts [array size MULTICAST] ;
parray MULTICAST ;
}


array set multicast { } ;

get_mroute_active [array get multicast] ;
puts [array size multicast] ;
parray multicast ;

代码的输出是:

3
MULTICAST(-1,id) = -1
MULTICAST(-1,mcast_group) = -1
MULTICAST(-1,mcast_source) = -1
0

你能帮我看看如何将“MULTICAST”变量分配给“multicast”吗?

最佳答案

简短的回答是:您不能从过程返回数组,因为数组不是值 — 它们是命名值的特殊命名集合。

有几种方法可以解决这个问题:

通常的方法是按名称传递数组,并让被调用过程就地修改数组。例如代码

proc foo {arrayName} {
upvar 1 $arrayName ary
incr ary(one)
}
set x(one) 1
foo x
puts $x(one)

将打印“2”,因为过程 foo 修改了调用方范围内指定数组中的特定值。

注意调用者如何传递数组的名称“x”而不是“它的值”(因为您不能从数组中提取值;但请参见下文),然后被调用的过程将局部变量绑定(bind)到该数组使用 upvar 按名称排列数组命令。

另一种方法是使用 array get and array set命令从数组中提取键和值,并分别用键和值填充数组。例如:

set x(one) 1
set x(two) 2
array set another [array get x]
parray another

会打印

another(one) = 1
another(two) = 2

array get 命令,给定一个数组,返回一个平面列表,其键和它们各自的值交错排列。通过这种方式,您可以从过程中返回数组的内容,然后让调用者对这些内容做任何它想做的事情,例如,使用array set命令来填充其范围内的另一个数组(可能与首先传递给该过程的数组相同)。

请注意,array set 具有合并语义:它不会在使用源列表插入/替换其值之前清空目标数组。

第三种(可能是最好的)方法是使用 dictionaries它们和数组一样是键/值映射,但它们本身是值,因此它们可以像其他值一样自由传递。这需要 Tcl 8.5 或更高版本(在 Tcl 8.4 中,你可以以包的形式使用 a backport of this code。使用 dicts 你可以这样得到它:

proc foo d {
dict set d one 2
return $d
}
set x [dict create]
dict set x one 1
set y [foo $x]
puts $y

这将打印“one 2”,因为过程修改了原始字典然后将其返回,然后调用者将其分配给另一个变量。

关于arrays - TCL:如何返回数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13664833/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com