geforce
geforce

Reputation: 79

inserting elements into List during Iteration in TCL/TK Scripting

I'm trying to add each input integer into a list and later sort it however I am having trouble adding each integer into the list during iteration.

code:

set l1 {1 2 3 4 5}

for {set i 0} {$i<[llength $l1]} {incr i} {
   set data [gets stdin]
   scan $data "%d" myint

   if $myint<=0 {break} # stop if non positive number is found

   set l1 {$myint} # supposed to add an input element into the list during iteration

}

puts $l1

Upvotes: 0

Views: 3086

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137567

Adding an element to the end of a list is easy; just use lappend instead of set:

lappend l1 $myint

When you come to sorting the list later, use lsort -integer, for example here with the puts:

puts [lsort -integer $l1]

(The lsort command works on values, not variables like lappend.)


However, it appears you're trying to actually input up to five values and sort those. If that's so, you'd be better off writing your code like this:

set l1 {}
for {set i 0} {$i < 5} {incr i} {
    set data [gets stdin]
    if {[eof stdin] || [scan $data "%d" myint] != 1 || $myint <= 0} {
        break
    }
    lappend l1 $myint
}
puts [lsort -integer $l1]

The differences here? I'm using an empty initial list. I'm testing for End-Of-File. I'm checking the result of scan (in case someone supplies a non-integer). I'm using a compound expression. It's all little things, but they help the code be more robust.

Upvotes: 1

Related Questions