【问题标题】:How to return the value from the proc using TCL如何使用 TCL 从 proc 返回值
【发布时间】:2016-01-30 13:02:08
【问题描述】:

我有一个示例过程

      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 }

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

【问题讨论】:

  • 请澄清您的问题。你到底在找什么?你认为你应该怎么做才能得到你想要的?像[exam b] 这样的东西只返回$b[exam d] 只返回$d 或者[exam a b] 来返回一个列表$a $b
  • 没有@jerry 这不是故意的,我期待“[exam 1st_run]”。在这种情况下,在 proc 执行之后如果我想获取存储在 b 中的值。例如,如果我执行' puts $1st_run(b)' 它应该有 "is" 谢谢你的帮助

标签: arrays list return tcl proc


【解决方案1】:

您可以使用dict 并选择可以使您的意图明确的键值映射:

return [dict create width 10 height 200 depth 8]

我认为除了复合数据结构或 yieldcoroutine 之外,Tcl 没有其他方法可以返回多个值。

【讨论】:

    【解决方案2】:

    返回多个值的常用方法是列表。这可以在调用站点与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
    

    您还可以返回字典。在这种情况下,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
    

    最后,您还可以在 exam 中使用 upvar 将调用者的变量带入作用域,尽管通常最明智的做法是只使用调用者为您提供名称的变量。

    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]"
    

    【讨论】:

    • 这里使用 upvar 和其他语言中的 pass-by-reference 意思一样吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 2011-01-05
    • 2011-09-21
    • 1970-01-01
    相关资源
    最近更新 更多