Home > Back-end >  Iteration in TCL using for each
Iteration in TCL using for each

Time:10-29

I'm trying to iterate the value using for each in TCL

This how i give input

./a.sh value1,value2

in the a.sh script

set var [lindex $argv 0]
set values [split $var ","]

foreach {set i 0} {$values} {
    puts "iterated once $i"
}

i want the iteration to happen twice since there are two values passed . but instead it is iterating only once

please help me on this

thanks in advance

CodePudding user response:

The foreach command, in its simplest form, takes a variable name, a list value, and a script to run for each element of the list. What you were passing was… weird in several ways at once. Look, here's a correct way of doing it:

set values [split $var ","]

foreach item $values {
    puts "iterated: $item"
}

If you want to count through, you should set up your own counter:

set values [split $var ","]

foreach item $values {
    set i [incr counter]
    puts "iterated #$i: $item"
}

That can be shortened to this:

foreach item [split $var ","] {
    puts "iterated #[incr counter]: $item"
}
  • Related