tclproc-objectupvar

TCL - return variable vs upvar and modify


Would like to take an advice from TCL professionals for best practice.

Say you want to construct a list with a specific data by using a proc. Now which is the best way?

proc processList { myList } {
   upvar $myList list_
    #append necessary data into list_
}

proc returnList {} {
    set list_ {} 
    #append necessary data into list_
    return $list_
}

set list1 {}
processList list1

set list2 [returnList ]

Which one of this practices is recommended?

EDIT: I am sorry but I can't understand consensus (and explanation) of people who answered to this question.


Solution

  • I virtually always use the second method:

    proc returnList {} {
        set result {}
        # ... accumulate the result like this ...
        lappend result a b c d e
        return $result
    }
    set lst [returnList]
    

    There's virtually no difference in memory usage or speed, but I find it easier to think functionally. Also, in Tcl 8.5 you can do the splitting up of the result list relatively simply (if that's what you need):

    set remainderList [lassign [returnList] firstValue secondValue]
    

    With that, you'd end up with a in $firstValue, b in secondValue, and c d e in $remainderList.