【问题标题】:Tcl nested proc taking output as input in nested procTcl嵌套过程将输出作为嵌套过程中的输入
【发布时间】:2014-12-10 17:31:24
【问题描述】:
proc str2hex { string } {
    set str [binary scan $string H* hex]
    puts $hex
    regsub -all (..) $hex {\1 } t1
    set res [format "%s" $t1 ]
    return $res 


    proc hex2str { $hex } {
        puts "HIIHI"
        foreach c [split $$hex ""] {
            if {![string is xdigit $c]} {
                return "#invalid $$hex"
            }
        }
        set hexa [binary format H* $$hex]
        return $hexa
    }
}

以上是将字符串转换为十六进制的简单代码。我制作了嵌套的proc,其中将“set str [binary scan $string H* hex]”脚本中的十六进制作为输入,以便将十六进制重新转换为字符串。请帮助我。

【问题讨论】:

    标签: nested tcl proc


    【解决方案1】:

    您通常不应该在 Tcl 的过程中嵌套过程;它的结果不是你所期望的。目前,Tcl proc 命令几乎不注意调用它的上下文(除了知道当前命名空间是什么),特别是它不会影响“内部”过程看到的变量。

    更重要的是,proc 是一个普通命令(恰好创建另一个命令),必须实际调用它才能执行任何操作。将它放在过程中唯一的return 之后将保证它完全没有效果。 Tcl 在这种情况下头脑非常简单(并且可以预测)。

    最后,不建议将$ 放在变量名中。这是合法的,但访问它的语法很尴尬(在你的情况下,它应该是${$hex})。


    如果您真的想要类似本地过程的东西,请考虑使用 apply 和 lambda 术语。它们是在 Tcl 8.5 中引入的。

    如果您使用的是 Tcl 8.6(现在推荐),那么您有一些更优雅的方式来执行这两个操作:

    proc str2hex {string {encoding "utf-8"}} {
        binary scan [encoding convertto $encoding $string] cu* bytes
        return [lmap value $bytes {format %02x $value}]
    }
    proc hex2str {hex {encoding "utf-8"}} {
        return [encoding convertfrom $encoding [binary format H* [join $hex ""]]]
    }
    

    (需要指定编码,否则在字节(binary scanbinary format 使用)和字符之间没有唯一的映射。但我们可以设置一个合理的默认值。)

    【讨论】:

    • 感谢@Donal Fellows 先生的指导。
    猜你喜欢
    • 1970-01-01
    • 2022-01-04
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    相关资源
    最近更新 更多