user707549
user707549

Reputation:

can we use foreach loop like this in tcl?

I have two list:

set lista {5 6}
set listb {8 9}

and the following code is used to loop the two lists:

foreach listaelement listbelement $lista $listb {
    puts $listaelement &listbelement 
}

how can we use foreach to achieve the output is:
first element from lista, first element from listb,
first element from lista, second element from listb,
second element from lista, first element from listb,
second element from lista, second element from listb,

5 8
5 9
6 8
6 9

Upvotes: 2

Views: 4983

Answers (2)

palanivel
palanivel

Reputation: 1

set lista {5 6}

set listb {8 9}


set indexb [expr ([llength $listb ] -1)]

foreach listano $lista {


for {set i 0 } {$i <= $indexb } {incr i} {

 set element [lindex $listb $i]

 puts "element is $listano $element"
 }
}

element is 5 8 element is 5 9 element is 6 8 element is 6 9

Upvotes: 0

Jackson
Jackson

Reputation: 5657

Just nesting the loops and using -nonewline should give the output you desire:

foreach listelementa $lista {
   foreach listelementb $listb {
      puts -nonewline "$listelementa  $listelementb  "
   }
}
puts ""

NB: You need to use quotes in the puts statement to stop Tcl interpreting the first argument as a channel id.

Tcl does allow you to reference multiple lists in a foreach statement

foreach listelementa $lista listelementb $listb {
    puts -nonewline "$listelementa  $listelementb  "
}
puts ""

However this gives 5 8 6 9 as its output - not what you require.

Edit: I'm pretty sure when I answered the question that the output was formatted as 1 line, if you actually want 1 line for each pair then you don't need the -nonewline on the puts and the trailing spaces and final puts can also go.

Upvotes: 6

Related Questions