Languages and Scripting
Showing results for 
Search instead for 
Did you mean: 

ksh two dimensional array ?

Stuart Abramson
Trusted Contributor

ksh two dimensional array ?

Can someone help me with this. Example prefered. in ksh.

I want to build a two-dimensional array with columns and rows like a spreadsheet and have the rightmost column be a total of each row, and the bottom row be a total of the entire column above it:

.......OS: AIX HP-UX Linux Total
Grp: A 5 10 2 17
B 0 3 9 12
-- -- -- -- --
Tot 5 13 11 29

I have never worked with two-dimensional arrays in ksh. Can you do that?

typeset A [10,10]
Rodney Hills
Honored Contributor

Re: ksh two dimensional array ?

two-dimensional arrays are not supported. You can simulate a two-dimensional with a one dimensional.

In your example-
ncols=10 ; # specifiy number of columns
p1=2 ; p2=3 ; # Desired position
# Convert position p1,p2 to offset in "A"
let "ix=ncols*(p1-1)+p2"


-- Rod Hills

(PS - another tool like "perl" might be a better way to go...)
There be dragons...
A. Clay Stephenson
Acclaimed Contributor

Re: ksh two dimensional array ?

That dog won't hunt. Arrays in the shell must be single dimensional.
Neiter A[2,3] or A[2][3] is valid shell syntax.

Probably the most straightforward approach would be awk --- but it only supports single-dimensional arrays as well BUT awks arrays will work. How can that be? Awk's array indices are associative rather that purely numeric like those of the shell.

This means that X[tom],X[harry], ... are perfectly valid so X[2,3] works as well because "2,3" is treated as a string.
If it ain't broke, I can fix that.
Fred Martin_1
Valued Contributor

Re: ksh two dimensional array ?

Haven't time to get to heavily involved but I'm wondering if a single-dimension array would work, if you apply an offset in your programming; we used to do this in the old Radio Shack TRS-80 days as it's BASIC also had no support for multi-dimensional arrays.

Example, with an array a[6,6] and the two indices being i,j ....

The single array a[x] would yield:

x = (i-1) * 6 + j

The only caviat is that the upper limit of one of the indices must be known or arbitrarily set, in this case 6.
Stuart Abramson
Trusted Contributor

Re: ksh two dimensional array ?

Thanks, all. I'll just bumble along with one array per row...