PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, November 10, 2022

[FIXED] How to pass multiple dict name to a proc

 November 10, 2022     dictionary, proc, tcl     No comments   

Issue

Let's say I don't know the name of the dict I have to pass, but I have list for it, so the setup looks like :

set mylist "dict_a dict_b"
dict set dict_a a 1
dict set dict_a b 2
dict set dict_b c 3
dict set dict_b d 4

But now I want to pass all my dict to a procedure (I still don't know the name of the dict, I know only the list of name). I would do something like :

proc test_dict {mylist} {
    foreach element $mylist {
        upvar 1 [subst $element] $element
    }
    foreach dict_ $mylist {
        puts " test of existence : [dict exists $dict_ a]"
    }
}

The answer of tcl is :

test of existence : 0
test of existence : 0

When called with :

test_dict $mylist

I should get 1 and 0 but not this. What is wrong in my proc ?


Solution

The real problem is that you are making local variables with the same name as the arguments. That's a tremendously bad plan as it means that the procedure can't safely use any variable name at all. It's also usually a bad idea to use subst in situations like this, particularly as it is evaluating in the context of the procedure.

Instead, you should use a single loop and reuse the upvar-bound variable:

proc test_dict {mylist} {
    foreach element $mylist {
        upvar 1 $element theDict
        puts " test of existence : [dict exists $theDict a]"
    }
}


Answered By - Donal Fellows
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing