Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Accessing a value in dynamically named array

I need to access a value in array which has been created in a dynamic way – meaning array’s name is stored in a variable.
To do this I try to use eval command but then get lost with the usage of $.
I do succeed to retrieve a key-value pair because no $ is required in a command like array get but what I need to use is array(key) pattern.

The expected simplified code would look like:

set arr foo;
set val1 v1;
set val2 v2;

eval "array set $arr \{
key1 $val1
key2 $val2
\}";

eval "set x \${$arr(key1)}";

As for the last line which is actually the failure, I’ve tried the following options:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

eval "set x \${$arr}(key1)";

or

eval "set x \$$arr(key1)"

and even more weird but with no success.

>Solution :

Remember that $var is shorthand for [set var]. So you could write the command as:

set x [set ${arr}(key1)]

But for these kind of situations, it’s probably easiest to use upvar:

upvar 0 $arr arrvar
set x $arrvar(key1)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading