Sree Ram
Sree Ram

Reputation: 61

foreach tcl list print each value in tcl and assign each value a variable in tcl list

proc mulval { addr } {
    set lst [list [split $addr "."]]
    set lst2 [list a b c d]
    foreach i [$lst2] j [$lst] {
        set $i [$j]
        puts "$i $j"
    }
}

The above code is to print each value present in list i.e lst2 and $lst are printed and assigned to variable name from $lst2 and value from $lst . The error shows in the code is "invalid command name "a b c d" "

Upvotes: 0

Views: 960

Answers (2)

Peter Lewerin
Peter Lewerin

Reputation: 13252

If you want to assign the elements of a list, there are several ways to do so. In your code, you did something like this:

foreach varName {a b c d} value [split $addr .] {set $varName $value}

This works, but is a bit overcomplicated. This invocation does the same thing:

foreach {a b c d} [split $addr .] {}
# can also be written as
foreach {a b c d} [split $addr .] break

If you have Tcl 8.5 or later, you should use lassign instead:

lassign [split $addr .] a b c d

Documentation: break, foreach, lassign, set, split

Upvotes: 0

Jerry
Jerry

Reputation: 71538

Square brackets are used for commands... remove them:

proc mulval { addr } {
    set lst [list [split $addr "."]]
    set lst2 [list a b c d]
    foreach i $lst2 j $lst {
        set $i $j
        puts "$i $j"
    }
}

Upvotes: 3

Related Questions