( ESNUG 240 Item 6 ) ---------------------------------------------- [5/9/96]
From: sgolson@trilobyte.com (Steve Golson)
Subject: (ESNUG 237 #4 238 #4) 2-D Arrays & Using "alias" To Mimic Functions
Hi, John,
David Ellement in ESNUG 237 #4 (and ESNUG 238 #4) gives a way to simulate
dimensional arrays in dc_shell. Dc_shell actually supports multi-dimensional
arrays, by using lists of lists. Here's an example:
dc_shell> row1 = {r1c1 r1c2 r1c3}
{"r1c1", "r1c2", "r1c3"}
dc_shell> row2 = {r2c1 r2c2 r2c3}
{"r2c1", "r2c2", "r2c3"}
dc_shell> row3 = {r3c1 r3c2 r3c3}
{"r3c1", "r3c2", "r3c3"}
Now combine these together into a list of lists:
dc_shell> array = {row1 row2 row3}
{{"r1c1", "r1c2", "r1c3"}, {"r2c1", "r2c2", "r2c3"},
{"r3c1", "r3c2", "r3c3"}}
If you want to add another row, be sure and put {} around the row when
you add it to the array:
dc_shell> row4 = {r4c1 r4c2 r4c3}
{"r4c1", "r4c2", "r4c3"}
dc_shell> array = array + {row4}
{{"r1c1", "r1c2", "r1c3"}, {"r2c1", "r2c2", "r2c3"},
{"r3c1", "r3c2", "r3c3"}, {"r4c1", "r4c2", "r4c3"}}
If you do a foreach on array, each element is itself a list:
dc_shell> foreach (element, array) { list element ; }
element = {"r1c1", "r1c2", "r1c3"}
element = {"r2c1", "r2c2", "r2c3"}
element = {"r3c1", "r3c2", "r3c3"}
element = {"r4c1", "r4c2", "r4c3"}
David also asks if there is a way to emulate functions without using global
variables to pass parameters. One technique is to use dc_shell_status to
pass arguments to an alias. The results can be returned in dc_shell_status
as well. Here is an example that extracts a specified element from a 2-D
array such as the one above:
alias get_element " \
foreach (element, dc_shell_status) { \
if (! list(row_index) ) { row_index = element ; continue ; } ; \
if (! list(col_index) ) { col_index = element ; continue ; } ; \
/* element contains the array */ \
remove_variable therow ; \
foreach (therow, element) { \
if (row_index==1) { break ; } ; \
row_index = row_index - 1 ; \
} ; \
/* now have therow */ \
remove_variable item ; \
foreach (item, therow) { \
if (col_index==1) { break ; } ; \
col_index = col_index - 1 ; \
} ; \
/* now have item */ \
/* clean up */ \
remove_variable row_index ; \
remove_variable col_index ; \
remove_variable therow ; \
/* leave item in dc_shell_status */ \
item = item ; \
} > /dev/null \
"
To get the third item in the second row of an array, pass a list of arguments
to the "function" get_element in dc_shell_status:
dc_shell> foo = {2 3 array}
{2, 3, {{"r1c1", "r1c2", "r1c3"}, {"r2c1", "r2c2", "r2c3"},
{"r3c1", "r3c2", "r3c3"}, {"r4c1", "r4c2", "r4c3"}}}
dc_shell> get_element
"r2c3"
dc_shell> the_answer = dc_shell_status
"r2c3"
The result is returned in dc_shell_status. Unfortunately any variable inside
your "function" are globally visible, so be sure to use remove_variable
whenever possible to keep things clean.
- Steve Golson
Trilobyte Systems
|
|