Version 8 of How to pass arrays

Updated 2002-04-17 08:01:16

[Explain what's meant.]


There are two choices for passing arrays both "into" and "out of" proc-s:

  • serialization, generally into a list with "array get ..."
  • local proxying of an external variable by use of upvar or occasionally uplevel

[Examples]

  • Array from pairlist: array set A {city Hamilton state TX zip 34567}
  • Array to pairlist: set L [array get A]
  • Copying an array: array set B [array get A] [but we have to show explicitly how this relates to proc-to-proc communication]

Removing keys with empty values from an array: Note that the array name is passed in, associated with local variable arr. The unsetting of elements with empty value, done in arr, in fact happens in the caller's original array.

 proc cleanArray arrName {
     upvar 1 $arrName arr
     foreach key [array names arr] {
         if {$arr($key) == ""} {unset arr($key)}
     }
 }

KBK (16 April 2002) - In Tcl 8.3 and beyond, it's much faster to say, simply:

    array unset arr

rather than looping through the result of [array names]. In earlier versions, you can say

    unset arr
    array set arr {}

but that has the disadvantage of messing up any traces that are extant on the array. RS: Indeed, but this clears the whole array - the specified task was to remove only those elements which have empty values.