1

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 Answer 1

4

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"
Sign up to request clarification or add additional context in comments.

1 Comment

You're going to have to double those backslashes to preserve them, or use braces instead of the double quotes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.