user3211264
user3211264

Reputation: 5

Nested for loop issue TCL

#!/bin/sh
# This is a trial program

puts "++++++++++++++++++++++++++++++++++++++++++++++++++"
set y "0.0.0.0"

set z [split $y "."]
puts "z=$z"
lreplace $z 0 5
puts "z $z"
set v [llength $z]
puts "length of array=  $v"
puts "in the loop-------->\n"
puts " "
incr v -1
puts $v
for {set ml $v } { $ml >= 0} { puts "$ml =ml"} {
    for { set nl [lindex $z $ml]} { $nl >=4} { puts "$nl=nl"} {
        puts $nl
        after 2000
        lset z  $ml $nl
        incr $nl
    }
    after 2000
    incr ml -1
}               

I am not able to enter the second for loop, is this a formatting issue ? gives me some weird error. I added the sleep just to check whats happening so ignore that.

Upvotes: 0

Views: 1272

Answers (2)

Peter Lewerin
Peter Lewerin

Reputation: 13282

Was it perchance something like this you intended?

# This is a trial program

puts "++++++++++++++++++++++++++++++++++++++++++++++++++"
set y "0.0.0.0"

set z [split $y "."]
puts "\$z=$z"
set v [llength $z]
# the term 'array' means associative array in Tcl, better use 'list'
puts "length of list=  $v"
puts "in the loop-------->\n\n"
incr v -1
puts "\$v=$v"
for {set ml $v} {$ml >= 0} {incr ml -1} {
    for {set nl [lindex $z $ml]} {$nl <= 4} {incr nl} {
        lset z $ml $nl
        puts $z
    }
}

Note that I've moved the incr command invocations to the third argument (the next command string, as the documentation puts it) of the for command invocations. You can put anything you want to run at the end of each iteration there, including puts commands as you did, but it's a convention and good practice to have the loop-control-changing commands (whatever they may be) there, and not much else.

Upvotes: 2

Niall Byrne
Niall Byrne

Reputation: 2460

In your code your inner loop is only evaluating if nl >=4. nl will be initialized as 0 from [lindex $z $ml]

Since you are incrementing $nl, my guess is you should change this line:

for { set nl [lindex $z $ml]} { $nl >=4} { puts "$nl=nl"} {

to this instead:

for { set nl [lindex $z $ml]} { $nl <=4} { puts "$nl=nl"} {

Upvotes: 2

Related Questions