Check existence of a key in an array with multiple keys in Tcl

Viewed 225

Is there a way to check a key existence, in an array with multiple keys? i.e...

    set test_arr(n1_temp,x_cell) 3

#As you can see that test_arr contains two keys named n1_temp and x_cell, now I am wondering if I can check the existence of a key named n1_temp

    if {[info exists test_arr(n1_temp)] } { ## not working 
    }

Please help.

-Regards, Shikha

2 Answers

As you can see that test_arr cotains two keys named n1_temp and x_cell

No, it has one key named n1_temp,x_cell.

Use a dict instead, which supports actual multi dimensional structures:

dict set test_dict n1_temp x_cell 3
if {[dict exists $test_dict n1_temp]} {
    # ...
}

Your array has one element, called n1_temp,x_cell with a comma in the name.

You can check for whether there is any element with n1_temp in the first part of the name by testing the length of the result list of array names test_arr n1_temp,* (that's a glob match). Be aware that this is an expensive operation in practice, as it has to do a linear scan of all the elements in the array.

if {[llength [array names test_arr n1_temp,*]]} {
    puts "There's an n1_temp,* element present"
}
Related