user707549
user707549

Reputation:

in tcl, how the following foreach statement works?

I have a question about foreach in tcl:

foreach id "6 8" {
   #do something here;
}

is this "6 8" a list? and what does "6 8" mean?

Upvotes: 1

Views: 259

Answers (2)

Hai Vu
Hai Vu

Reputation: 40688

foreach id "6 8" {
    # do something
}

In this context, "6 8" is a list of two elements, 6 and 8. The loop for assign id first to 6, enter the loop's body. The next time around, id will be 8 and enter the loop's body. When it runs out of items in the list, the loop exits.

Upvotes: 2

RHSeeger
RHSeeger

Reputation: 16262

The main thing to remember is that Tcl doesn't have types, per se, at least not in a way that the user should need to worry about them. Rather, each value is a string and each command tries to treat it as the type of value it needs.

For example:

set value "1"
expr {$value + 1} ; # treat $value as a number
lindex $value 0   ; # treat $value as a list

For your code, the value 6 8 is being interpreted as a list by the foreach command, with the value 6 and 8. The double quotes around the value just group the content inside them as a single value. They (the dqs) don't signify any specific type (ie, string, list, number).

Upvotes: 3

Related Questions