如何使用 TCL 从 proc 返回值

vel*_*ian 0 arrays return list tcl proc

我有一个示例程序

      proc exam {return_value} {

        set input "This is my world" 
         regexp {(This) (is) (my) (world)} $input all a b c d 
         set x "$a $b $c $d" 
    return x }
Run Code Online (Sandbox Code Playgroud)

在执行上述过程之后,我将获得单个列表中的所有 abcd 值,因此,如果我只想要上述过程中的 b 值,现在正在执行 [lindex [exam] 1]。我正在寻找其他方式以不同的方式获取输出,而不是使用 lindex 或 returnun_value(b) 可以给出我的预期输出

Don*_*ows 5

返回多个值的常用方法是作为列表。这可以在调用站点使用,lassign以便列表立即分解为多个变量。

proc exam {args} {
    set input "This is my world" 
    regexp {(This) (is) (my) (world)} $input all a b c d 
    set x "$a $b $c $d" 
    return $x
}

lassign [exam ...] p d q bach
Run Code Online (Sandbox Code Playgroud)

您还可以返回字典。在这种情况下,dict with有一个方便的解压方法:

proc exam {args} {
    set input "This is my world" 
    regexp {(This) (is) (my) (world)} $input all a b c d 
    return [dict create a $a b $b c $c d $d]
}

set result [exam ...]
dict with result {}
# Now just use $a, $b, $c and $d
Run Code Online (Sandbox Code Playgroud)

最后,您还可以使用upvarinsideexam将调用者的变量带入作用域,尽管通常最明智的做法是仅使用调用者为您提供名称的变量来执行此操作。

proc exam {return_var} {
    upvar 1 $return_var var
    set input "This is my world" 
    regexp {(This) (is) (my) (world)} $input all a b c d 
    set var "$a $b $c $d" 
    return
}

exam myResults
puts "the third element is now [lindex $myResults 2]"
Run Code Online (Sandbox Code Playgroud)