hi, I was wondering if there was a good way to create an array within a function, where the name is based on a passed argument? I tried this:
_____________________________
func(){ #take in 1st arg as the arrayname
arrayName=$1
let i=0
while read line
do
arrayName[$i]=${line}
let i+=1
done
}
func "offsets"
_______________________________
So I was trying to name the array "offsets", but the way in which I have it just renames the array to whatever is in the first line of the file. I want to be able to call the function multiple times and set different array names.
adding a dollar sign to just reference the name doesn't work:
$arrayName[$i]=${line}
You probably can do this. I am not at a terminal now to play with any code but you can research this by looking at the man pages for eval and typeset , specifically, see the -A flag
Perderabo: I gave it a try but it just placed the name of the array (offsets) in the first postion and did not put anything else in the array.
google: I'll take a look at those. I tried eval a couple times, but nothing so far.
I did come up with a workaround. I just changed the original code I posted, by starting the variable 'i' at 1 instead of 0. This allows the name of the array to be placed at the 0 postion and the data from 1...n. I just have to be aware in the rest of the script that the data will always start at 1.
I would still like to find another way, without having to use the little workaround though.
#! /usr/bin/ksh
func(){
#take in 1st arg as the arrayname
arrayName=$1
let i=0
while read line
do
eval ${arrayName}[\$i]=\${line}
let i+=1
done
}
func "offsets"
echo offsets = ${offsets[*]}
exit 0
$ ./ar
one
two
three
^Doffsets = one two three
$
yeah your right it works. I have no idea what the problem was, I copied the specific line in and it didn't work with everything else the same. But then copied in the whole function and it worked fine. maybe a null character or something.