Search code examples
arraystclprocedure

How to pass multiple arrays in tcl proc?


enter code here

I want to pass multiple arrays to tcl proc for a specific task.

say I have List of Array Names

set array_names [list abc pqr xyz]

each array contains

array set abc {
      red true
      blue false
      green true
      yellow false
}
array set pqr {
      red false
      blue true
      green false
      yellow true
}

same for xyz array

Without proc I am able to perform below task but need to create a proc for the same

foreach RS $array_names {
   foreach {arr_ind ind_value} [array get $RS] {
       puts "set $RS\_$arr_ind $ind_value"
}}

It will output

set abc_yellow false
set abc_blue false
set abc_green true
set abc_red true
set pqr_yellow true
set pqr_blue true
set pqr_green false
set pqr_red false

Solution

  • You can make use of upvar command to achieve this.

     proc test {array_names} {
            foreach elem $array_names {
                    upvar $elem __array
                    foreach {arr_ind ind_value} [array get __array] {
                            puts "set $elem\_$arr_ind $ind_value"
                    }
            }
    }
    

    Call the procedure as,

    test $array_names
    

    Reference : upvar