首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用puts写入文件并在puts中调用proc

使用puts写入文件并在puts中调用proc
EN

Stack Overflow用户
提问于 2014-10-14 18:45:32
回答 3查看 84关注 0票数 0

我在尝试编写的以下代码中遇到了问题:

代码语言:javascript
复制
set temp [open "check.txt" w+]
puts $temp "hello"
proc print_message {a b} {
    puts "$a"
    puts "$b"
    return 1
}
print_message 3 4
puts "[print_message 5 7]"
puts $temp "[print_message 5 7]"
print_message 8 9

在puts中,"print_message 5 7“、5和7打印在屏幕上,1打印在文件check.txt中。如何在文本文件中而不是屏幕上打印5和7。

EN

回答 3

Stack Overflow用户

发布于 2014-10-14 18:58:52

您可以按如下方式重写您的proc,

代码语言:javascript
复制
proc print_message {a b { handle stdout } } {   
        # Using default args in proc. If nothing is passed, then
        # 'handle' will have the value of 'stdout'. 
        puts $handle "$a"
        puts $handle "$b"
        return 1
}

如果传递了任何参数,则它将写入该文件句柄。否则,它将位于终端的stdout上。

代码语言:javascript
复制
puts "[print_message 5 7 $temp]" ; # This will write into the file
puts "[print_message 5 7]"; # This will write into the stdout
票数 1
EN

Stack Overflow用户

发布于 2014-10-14 23:45:25

我会像puts本身一样编写它,并将可选通道作为第一个参数:

代码语言:javascript
复制
proc print_message {args} {
    switch [llength $args] {
        3 {lassign $args chan a b}
        2 {set chan stdout; lassign $args a b}
        default {error "wrong # args: should be \"print_message ?channelId? a b\""}
    }
    puts $chan $a
    puts $chan $b
}

print_message 3 4
print_message 5 7
print_message $temp  5 7
print_message 8 9

我假设您实际上并不想在stdout上看到"1“。

票数 0
EN

Stack Overflow用户

发布于 2014-10-15 04:32:12

很难确定你想在这里做什么。

如果你想在屏幕上和文件中打印出相同的内容,你可以这样做:

代码语言:javascript
复制
proc print_message {a b} {
    puts $a
    puts $b
    format %s\n%s\n $a $b
}

puts -nonewline $temp [print_message 5 7]

如果你只想格式化两个值到一行,你可以这样做:

代码语言:javascript
复制
proc print_message {a b} {
    format %s\n%s\n $a $b
}

puts -nonewline       [print_message 5 7] ;# to screen
puts -nonewline $temp [print_message 5 7] ;# to file

文档:formatprocputs

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26358885

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档