[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Syntax error in a Map/Hash initializer -- why isn't this supported?

From: Greg Wooledge
Subject: Re: Syntax error in a Map/Hash initializer -- why isn't this supported?
Date: Tue, 11 Aug 2020 07:34:56 -0400
User-agent: Mutt/1.10.1 (2018-07-13)

> > "Can bash please implement multidimensional arrays as I think they're
> > nifty and would like to use them."
> It seems that Chet has never been interested, and no one else has
> stepped up to contribute.

A large reason for this is because bash is a shell, not a programming
language.  Another reason is that there are already ways to work
around the "issue".

The standard way to implement something that works like a multidimensional
array is to use an associative array, and construct a key string out of
your multiple indices, using some delimiter character that can't appear
in any of the indices.

For example, if your indices are integers, you could use a comma
as the delimiter.  Then:

declare -A grid=( [0,0]=foo [0,1]=bar [0,2]=baz )
x=0 y=2
echo "${grid[$x,$y]}"

This prints "baz" as expected.

Another way which *only* works when your indices are small non-negative
integers is to use a sparse indexed array, and construct a key index
of the form  i + (A)j + (A^2)k + ...  where A is some suitably large
constant chosen for your particular problem.  For example, to store
up to a 100x100 grid, we can choose A = 100, and let the individual
indices run from 0 to 99.

unset grid
grid=( [0+100*0]=foo [0+100*1]=bar [0+100*2]=baz )
x=0 y=2
echo "${grid[x+100*y]}"

This has the advantage of working in bash versions 2 and 3 which lack
associative arrays, and the disadvantages of requiring numerical indices,
and a strict up-front limit on the dimensions of your matrix.

If you can't abide using "hacks" to implement your own multidimensional
arrays, then bash isn't the right language for your project.  Choose a
different one.

reply via email to

[Prev in Thread] Current Thread [Next in Thread]