Tcl的语法 很"牛"

    目前正在操练TCL,做了两个练习。题目与源码如下:

    1)写一个过程mysort,有两个参数,input是字符串,type是逆序方式(分为bylist方式和bystring方式,默认bylist方式)。
        
函数原型:proc mysort {input {type bylist}} 
        
例如:
        mysort "hello" bystring 返回的结果是 olleh
        mysort "a b c d" bylist 返回的结果是 d c b a
        mysort "a b c d" 返回的结果是 d c b a
        mysort "abcd" *** 返回的结果是 "type不匹配!请指定bylist或bystring方式"
       
         

#过程mysort,input是字符串,type是逆序方式
proc mysort {input {type bylist}} {
    
set sl [string length $input]
    
set rs ""
    
if {[string compare $type "bystring"]==0 && $sl > 0} {
        
while {$sl>0} {  
        
set temp [string index $input [expr $sl-1]]
        append rs $temp
        incr sl 
-1
        }
        puts $rs
     } 
elseif {[string compare $type "bylist"]==0 && $sl > 0} {
            
set i [expr [llength $input] -1
            
while { $i>=0} { 
            lappend rs [lindex $input $i] 
            incr i 
-1 
        }
        puts $rs
     } 
else {
         puts 
"type不匹配!请指定bylist或bystring方式"
     }
}

2)写一个文件处理函数,将in.txt里的内容读出来,并按照如下形式组合,然后讲组合内容存到out.txt中。
注:
1)     in.txt --> out.txt  的过程中,true转为1,false转为0
2)     每行固定都有9个参数
3)     每行的参数都依次转为单列
4)     函数原型 convert {sourcefile targetfile}
        例如: convert "c:/in.txt" "c:/out.txt"
5)     通过tclsh来调用(用source命令)

in.txt文件形式:

=======================
1 0 1 1 1 23 43 89 99
true false false true true 1 2 3 4
0 0 0 0 1 100 299 300 18
false 0 1 true 1 10 20 10 11
=======================

out.txt文件形式:
=======================
1
0
1
1
1
23
43
89
99
1
0
0
1
1
1
2
3
4
0
0
0
0
1
100
299
300
18
0
0
1
1
1
10
20
10
11
=======================

puts "Please input sourcefile name: "
set sourcefile [gets stdin]
puts 
"Please input targetfile name: "
set targetfile [gets stdin]

proc convert {sourcefile targetfile} {
    #
set sourcefile "c:/in.txt"
    #
set targetfile "c:/out.txt"
    
set line ""                 ;#建立临时list变量
    
set sf [open $sourcefile r] ;#打开源文件
    
set tf [open $targetfile w] ;#打开目标文件
    
    
while {![eof $sf]} { 
        gets $sf line
        
set i [expr [llength $line] -9]
        
while { $i<9} {
            
set b [lindex $line $i]              
            
if {[string compare $b "true"]==0} {  ;#进行true,false替换
                
set b 1
            } 
elseif {[string compare $b "false"]==0} {
                
set b 0
            } 
            puts $tf $b
            incr i
        }
        puts $line
    }
    close $sf                   ;#关闭源文件
    close $tf                   ;#关闭目标文件
}

convert $sourcefile $targetfile

posted on 2008-01-20 15:59  LeoWang  阅读(421)  评论(0编辑  收藏  举报

导航