0

I'm trying to retrieve a list of numbers from an array (in a txt file) and to do mathematical operations on them then to set them back in a list of the same format. The txt file looks like this (format is fixed):

1000 2000 3000 4000

I want to read that txt file then to create another list which will be saved in a different text file:

1010 1100 2010 2100 3010 3100 4010 40100 # which is basically adding 10 and 100 to each index.

Here what I've done so far (I'm a very beginner in tcl !)

set zonefile [open "mytxtfile.txt" r]
gets $zonefile
set my_list [gets $zonefile]
puts $my_list

# Check that there is at least one location defined
if { [llength $my_list] == 0 } {
    error "No domain are defined in the system parameters workbook"
} else {
    puts "OK !"
}
puts [llength my_list]

# this returns 1, which from my understanding means I only have 1 value in my array instead of 4
set c1 [string range $my_list 0 3]
set c2 [string range $my_list 5 8]
set c3 [string range $my_list 10 13]
set c4 [string range $my_list 15 18]
array set domain_list ([lindex $c1 0] [lindex $c2 0])
# I thought this would create an array of 1000 2000 3000 4000 but this doesn't work

Thanks a lot !

1 Answer 1

2

I think you're making it more complicated than it needs to be. You don't need to know indexes of elements at all, just use foreach and lappend to build the output array:

set in [open input.txt r]
set a {}
foreach n [split [read $in] " "] {
    lappend a [expr {$n + 10}] [expr {$n + 100}]
}
close $in
set out [open output.txt w]
puts $out $a
close $out

If input.txt is:

1000 2000 3000 4000

output.txt will be

1010 1100 2010 2100 3010 3100 4010 4100
Sign up to request clarification or add additional context in comments.

2 Comments

@flavie, note the use of split here -- not every string can be safely treated as a list, so best to code defensively.
It is working ! I just forgot to mention that my list of numbers was starting on the line 2 (I have a header on line 1). Just now need to start the reading form line 2 and add my header in the output file. Thanks and sorry for my stupidity !

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.