Jonjilla
Jonjilla

Reputation: 463

in Tcl, when should use use set vs unset to prepare to use a variable

In my scripts, when using a variable, I generally empty the contents of a variable to ensure that the list appends are clean. Something like the following

set var1 [list]
foreach var2 {a b c} {
  lappend var1 $var2
}

But it seems like unsetting the variable first would accomplish the same thing. Something like this

unset -nocomplain var1
foreach var2 {a b c} {
  lappend var1 $var2
}

Is there any advantage for using one vs the other?

Upvotes: 1

Views: 513

Answers (2)

Peter Lewerin
Peter Lewerin

Reputation: 13252

As Donal wrote, set var {}. Internally, the same value will be assigned regardless of whether you assign {}, [list] etc. Yes, it will shimmer, and no, it won't be a problem.

Regarding set vs unset: while you can use them as you see fit, they mostly serve different patterns. In the assign-empty-value pattern, you want a variable ready for writing or reading, with a predefined, empty value. In the remove-from-scope pattern you want the name to be unused (it won't be unusable: you can still assign to / create it). Unless you're after something like the second pattern, you probably won't have much serious use for unset.

Upvotes: 0

Donal Fellows
Donal Fellows

Reputation: 137627

It doesn't make any difference in this case. If I was to write such a loop in my own code, I would be more likely to use set var {} since that is the empty list literal (as well as being the empty string, the empty dictionary, the empty script, etc.) but there isn't any execution time difference to speak of. It just reflects how I think about scripts.

Of course, if you are doing something where it does matter, use the right one for that case.

Upvotes: 2

Related Questions