【问题标题】:Equivalent one liner in tcl for an if statement and puts等效于 tcl 中的一个衬里用于 if 语句和 puts
【发布时间】:2021-04-10 00:01:36
【问题描述】:

我在 tcl 中有代码,我只想在启用变量的情况下打印这些代码。如果可能的话,我想在一行中做到这一点。

#in perl 
print "Device name $dev" if(-e $debug);
#in tcl
if {[tvf::svrf debug ]}{
    puts "Device name is $dev"
}

【问题讨论】:

标签: perl unix tcl


【解决方案1】:
if {[tvf::svrf debug ]} { puts "Device name is $dev" }

【讨论】:

  • 还有什么比这更好的吗?
  • “更好”在很大程度上是一个角度问题。世界上不缺换行符。
【解决方案2】:

我会把它分成多行除非你会在很多地方做出这个决定。如果你在很多地方都在做,最好设置一个程序:

# A single-line way to write this
proc writeDebugMessage args [lindex {{} {puts [lindex $args 0]}} [tvf::svrf debug]]

# At the places where you want to print a message in some cases
writeDebugMessage "Device name is $dev"

该过程定义是编写这个较长版本的单行方式:

if {[tvf::svrf debug]} {
    proc writeDebugMessage args {puts [lindex $args 0]}
} else {
    # This exact form of procedure gets bytecode compiled into nothingness; max efficiency!
    proc writeDebugMessage args {}
}

如果这是我的真实代码,我会使用更长的版本甚至更冗长!


一个真正的单行版本是可能的,并且尽可能短:

[lindex {list puts} [tvf::svrf debug]] "Device name is $dev"

不推荐!定义帮助程序会产生更易读的代码!

【讨论】:

  • 我真的希望现在没有代码在 OP 的工作中使用最后一个。
【解决方案3】:

Tcl 不支持 Perl 的语句修饰符。这完全归功于 Tcl 的 command arg arg ... 语法。

如果你喜欢这种风格,你可以创建一个辅助过程:

proc do {script if condition} {
    if {$if ne "if"} {
        error "some usage message"
    }
    if {[uplevel [list expr $condition]]} {
        uplevel $script
    }
}

然后:

% set debug true
true
% do {puts "I'm debugging"} if {$debug}
I'm debugging
% set debug false
false
% do {puts "I'm debugging"} if {$debug}
%

do proc 可以用do ... while ... 等进行扩展。

【讨论】:

    【解决方案4】:
    set dev debug_device
    interp alias {} print {} apply {{args {dbg 0}} {expr {$dbg?$args:{}}}}
    
    set debug true
    print "Device name is $dev" $debug
    

    使用 apply 作为匿名函数的快速单行别名。

    【讨论】:

      【解决方案5】:

      没有什么可以正确地阻止您在 Tcl 中定义这个简单的 Perl 命令:

      proc print {msg args} {
        # never mind, this is for fun only
        if {[string match "if(-e *)" $args]} {
          if {[string range $args 6 end-1]} {puts $msg}
        } else {
          # other Perl stuff whatever it was
        }
      }
      

      ...并在 Tcl 中使用这个 Perlish print

      set dev "'Perl device'"
      # ------------
      set debug true
      print "Device name $dev" if(-e $debug)
      print "Is it true?" if(-e true)
      print "Is it false?" if(-e false)
      # ------------
      set debug false
      print "2. Device name $dev" if(-e $debug)
      print "2. Is it true?" if(-e true)
      print "2. Is it false?" if(-e false)
      

      这样你可以在 Tcl 中重新定义所有 Perl ;-)

      【讨论】:

        猜你喜欢
        • 2015-07-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-01
        • 2014-04-01
        • 2012-05-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多