Accessing Elements

Updated July 2015

To refer to the value of an element (i.e. use it as a source string in an expression), just use the standard array syntax with the key as the subscript:

print "The capital of "; state$; " is "; $capitals(state$)

For ordered maps with unformatted elements (i.e. blob, binary, structures, X type), you can use the subscripted array reference in the same was as you would the MAP1 (X type) variable or structure,e.g.

Map1 Prod’rec

Map2 sku$,s,10

Map2 price,f,6

Map2 qtyonh,I,4

Dimx $products,ordmap(varstr;varx)

Prod’rec = $products(“AB-1234”)    ! retrieve map element into structure

? “Product “;sku$;” price is “;price;” qtyonh is”;qtyonh

Write #ch, $products(“AB-1234”)   ! or use element directly as structure

 

The traditional mapped “structure” in the above example could also be replaced with a formal structure (defined via DEFSTRUCT), in which case after retrieving the element into the structure, you would use the structure.member syntax to access the members.

Note that when accessing ordered map elements by key, just as with indexed file access, you really need to test for the possibility that the element does not exist. A non-existent element will return the special value .NULL, which for varstr type elements can be tested for with a standard string comparison, i.e.

City$ = $capitals(state$)

If City$ = .NULL then

? “capital of “;state$;” is undefined”

Else

? “capital of “;state$;” is “;City$

Endif

 

For varstr elements, attempting to print the .NULL value will display “<null>”, which may be acceptable in some casual situations.

For varx elements, the .NULL value cannot be tested with a simple string comparison, and attempting to reference members of a null structure will result in undefined values. Instead, you must use the function .ISNULL(var) to test it, so the above example should really be coded as:

Prod’rec = $products(“AB-1234”)    ! retrieve map element into structure

If .ISNULL(Prod’rec) then

? “No such product defined”

else

? “Product “;sku$;” price is “;price;” qtyonh is”;qtyonh

endif

 

The .ISNULL(var) test works equally well for both varstr and varx elements, so the best strategy is to use it in all cases, thus avoiding difficult-to-diagnose bugs resulting from accidentally attempting to compare a varx value to the .NULL string value. So the varstr example above would be better coded as:

City$ = $capitals(state$)

If .ISNULL(City$) then         ! (better than testing if City$ = .NULL)