Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > gnu.bash.bug > #16738

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

From Greg Wooledge <wooledg@eeg.ccf.org>
Newsgroups gnu.bash.bug
Subject Re: Syntax error in a Map/Hash initializer -- why isn't this supported?
Date 2020-08-11 07:34 -0400
Message-ID <mailman.1533.1597145727.2739.bug-bash@gnu.org> (permalink)
References <CALOnQv74zqDBOQoSRhH07oQ7eu5qLsdzU8r4d48==eZhB4YE3g@mail.gmail.com> <ad562bc9-4ca4-2b50-c1f8-2fe8d30653b3@archlinux.org> <8371B746-DDAB-48B1-932B-8197E3658255@larryv.me> <20200811113456.GJ931@eeg.ccf.org>

Show all headers | View raw


> > "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.

Back to gnu.bash.bug | Previous | Next | Find similar


Thread

Re: Syntax error in a Map/Hash initializer -- why isn't this supported? Greg Wooledge <wooledg@eeg.ccf.org> - 2020-08-11 07:34 -0400

csiph-web