Sapir Melamed
Sapir Melamed

Reputation: 25

how to use correctly in the split command in tcl

I'm new to tcl and I tried to use in split command my goal is to access to a path and delete the line number that are written in temp.txt

//this block was successful    
set f [open wave_test.txt]
set pid [open temp.txt "w+"] 
while {[gets $f line] != -1} {
    if {[regexp {#spg_backref :\s+(.*)} $line all value]} {
        puts $pid $value
    }
}
close $f

//here I have a problem while printing the value of data that doesn't exist 
in the temp.txt file
set data [split $pid "\n"]
puts "the data is $data\n"
close $pid

//I think that there is a problem using " as a token in split command
foreach line $data {
    puts "set my list\n"
    set my_list [split $line ""]
    puts "my_list is $my_list\n"
    set path [lindex $my_list 1]
    set line_num [lindex $my_list 1]
    puts "the path is $path\n"
    puts "the line number is $line_num\n"
}


//I copied some lines from the temp.txt file
"/c/pages/smelamed/glass/var/tests/my_glass/rules/top.txt" 1145
"/c/pages/smelamed/glass/var/tests/my_glass/rules/target.txt" 114
"/c/pages/smelamed/glass/var/tests/my_glass/rules/other.txt" 3

Thank you!

Upvotes: 1

Views: 1562

Answers (2)

HanT
HanT

Reputation: 151

split $line "" means splitting $line in a list of separate character. So if you have a string "abc", then set mylist [split abc ""] will give {a b c} and lindex $mylist 1 equals 'b'. Simply write: set path [lindex $line 0], because lindex automatically interprets $line as a list.

Using split $line may cause errors if the path name contains spaces.

You may also consider lassign $line path line_num to set both path and line_num in one command.

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246827

In this line set data [split $pid "\n"], $pid is the file handle of the open "temp.txt" file, not the contents of the file

Since you opened the file w+, you can do

# write to the file
...
# jump to beginning of file and read it
seek $pid 0
set data [split [read -nonewline $pid] \n]
close $pid

Upvotes: 1

Related Questions