Tcl 嵌套 proc 将输出作为嵌套 proc 中的输入 [英] Tcl nested proc taking output as input in nested proc

查看:38
本文介绍了Tcl 嵌套 proc 将输出作为嵌套 proc 中的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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
    }
}

以上是字符串转十六进制的简单代码.我做了嵌套过程,其中一个来自set str [binary scan $string H* hex]"脚本的十六进制作为输入以便将十六进制重新转换为字符串.请帮助我.

The above is simple code for conversion of string to hexadecimal.I have made nested proc,where a hex from "set str [binary scan $string H* hex]" script is taken as input so as to re -convert the hex to string .Plz help me .

推荐答案

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

You shouldn't normally nest procedures inside procedures in Tcl; the results of it are not what you're expecting. Currently, the Tcl proc command takes almost no notice of the context in which it is called (except for knowing what the current namespace is), and in particular it does not affect what the "inner" procedure sees for variables.

更重要的是,proc 是一个普通命令(碰巧创建另一个命令)并且必须实际调用它才能执行任何操作.将它放在过程中唯一的 return 之后将保证它根本不起作用.Tcl 非常简单(并且可以预测).

What's more, proc is an ordinary command (that happens to create another command) and must actually be called for it to do anything. Putting it after the only return in a procedure will guarantee that it has no effect at all. Tcl's very simple-minded (and predictable) that way.

最后,将 $ 放在变量名中是不可取的.这是合法的,但访问它的语法很尴尬(在您的情况下,它将是 ${$hex}).

Finally, it's inadvisable to put $ in a variable name. It's legal, but the syntax for accessing it is awkward (in your case, it would be ${$hex}).

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

If you really want local procedure-like things, consider using apply and a lambda term. They were introduced in Tcl 8.5.

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

If you're using Tcl 8.6 (recommended now) then you've got some more elegant ways of doing these two operations:

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 可以使用——和字符.但是我们可以设置一个合理的默认值.)

(The encoding needs to be specified as otherwise there isn't a unique mapping between bytes — which binary scan and binary format work with — and characters. But we can set a sensible default.)

这篇关于Tcl 嵌套 proc 将输出作为嵌套 proc 中的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆