Re: ksh two dimensional array ? (1273 Views)
Reply
Trusted Contributor
Stuart Abramson
Posts: 278
Registered: ‎07-15-1999
Message 1 of 5 (1,273 Views)

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]
A[2,3]=9
Please use plain text.
Honored Contributor
Rodney Hills
Posts: 1,679
Registered: ‎09-09-1996
Message 2 of 5 (1,273 Views)

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"
A[$ix]=9

HTH

-- Rod Hills

(PS - another tool like "perl" might be a better way to go...)
There be dragons...
Please use plain text.
Acclaimed Contributor
A. Clay Stephenson
Posts: 17,825
Registered: ‎07-16-1998
Message 3 of 5 (1,273 Views)

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.
Please use plain text.
Valued Contributor
Fred Martin_1
Posts: 1,044
Registered: ‎07-30-1998
Message 4 of 5 (1,273 Views)

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.
fmartin@applicatorssales.com
Please use plain text.
Trusted Contributor
Stuart Abramson
Posts: 278
Registered: ‎07-15-1999
Message 5 of 5 (1,273 Views)

Re: ksh two dimensional array ?

Thanks, all. I'll just bumble along with one array per row...
Please use plain text.
The opinions expressed above are the personal opinions of the authors, not of HP. By using this site, you accept the Terms of Use and Rules of Participation