A.G.Progm.Enthusiast
A.G.Progm.Enthusiast

Reputation: 1010

How to access a list, that is passed to a proc to be modified, outside of that proc in TCL?

In my TCL script I am passing an empty list as argument to a proc. Inside the proc, I am adding values to the list. But outside of that proc, the values of list is not reflected. How can I access the same list which is modified within the proc ?

Note : I do not want to return from the proc due to some reasons which I have not mentioned here in the interest of keeping my requirement simple.

proc addNames { names } {
    lappend names tom
    lappend names harry
    puts $names
}

set names {}
addNames $names 

puts "Outside of proc: names"
puts $names 

Upvotes: 1

Views: 55

Answers (1)

TrojanName
TrojanName

Reputation: 5375

If you don't want to use return in your proc, then you could use upvar e.g.

proc addNames { names } {
    upvar 1 names n
    lappend n tom
    lappend n harry
}

set names {}
addNames $names 

However, note that this creates a dependency in your proc on the existence of names in the calling environment. A more flexible approach might be to pass in a parameter with the name of the names variable:

proc addNames {varName} {
    upvar 1 $varName n
    lappend n tom
    lappend n harry
}

set names {}
addNames names

Upvotes: 2

Related Questions