Reputation: 993
I am new to TCL scripting. I am trying to insert an element (in a list) in the 5th position. This list has got no values (empty list) initially.
I tried with "linsert" command, but the problem is it cannot insert an element at the position specified by me. Following is the code snippet,
set newlist {}
set newlist [linsert $newlist 5 value_to_be_inserted]
This code doesnot inserts the element in the 5th position, rather it inserts at the beginning in the 0th element. How can i achieve this task.
Any help will be really good for my understanding.
Upvotes: 0
Views: 2866
Reputation: 1798
If you want the behaviour of e.g. JavaScript, where the list is expanded with empty elements if the index is greater than the length, I think you'll have to make a procedure.
proc expandInsert {list index args} {
set nEmpties [expr {$index - [llength $list]}]
if {$nEmpties > 0} {
lappend list {*}[lrepeat $nEmpties ""]
}
# insert or append args
return $list
}
Upvotes: 3
Reputation: 185671
Your list has zero elements. How can you possibly insert at the 5th position when there is no 5th position to insert at? What resulting list are you expecting to have? The only thing I can possibly think of would be to have 5 empty elements followed by your element, which you can achieve simply by saying
set newlist [list {} {} {} {} {} value_to_be_inserted]
Upvotes: 3