How to parse a text file in tcl using separators?

廉价感情. 提交于 2020-01-06 01:35:27

问题


I have a text file of the format

35|46

36|49

37|51

38|22

40|1

39|36

41|4

I have to read the file into an array across the separator "|" where left side will be the key of the array and right side will be the value.

I have used the following code

foreach {line} [split [read $lFile] \n] {
    #puts $line
    foreach {lStr} [split $line |] {
        if { $lStr!="" } {
            set lPartNumber [lindex $lStr 0]
            set lNodeNumber [lindex $lStr 1]
            set ::capPartsInterConnected::lMapPartNumberToNodeNumber($lPartNumber) $lNodeNumber

        }
    }

}

close $lFile

I am not able to read the left side of the separator "|". How to do it?

And similarly for this :

35|C:\AI\DESIGNS\SAMPLEDSN50\BENCH_WORKLIB.OLB|R

36|C:\AI\DESIGNS\SAMPLEDSN50\BENCH_WORKLIB.OLB|R

I need to assign all three strings in different variables


回答1:


You are making mistake in the foreach where the result of split will be assigned to a loop variable lStr where it will contain only one value at a time causing the failure.

With lassign, this can be performed easily.

set fp [open input.txt r]
set data [split [read $fp] \n]
close $fp

foreach line $data {
    if {$line eq {}} {
        continue
    }
    lassign [split $line | ] key value
    set result($key) $value
}   
parray result

lassign [split "35|C:\\AI\\DESIGNS\\SAMPLEDSN50\\BENCH_WORKLIB.OLB|R" |] num userDir name
puts "num : $num"
puts "userDir : $userDir" 
puts "name : $name"


来源:https://stackoverflow.com/questions/31667652/how-to-parse-a-text-file-in-tcl-using-separators

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!