Is there any way to *safely* pass a variable number of namerefs to a function?
I am
trying to copy the contents of multiple arrays into a new one. This means that
the
function will receive an arbitrary number of arguments all of which are
variable names
that are supposed to be bound to namerefs.
The following copy_arrays function works so long as the nameref variable does
not have
the same name as what it's referencing.
function copy_arrays {
# copy_arrays dest src...
#
# Copies any number of source arrays into the destination.
nameref newarr=$1 arr
integer i index=0
shift
for arr
do
for (( i=0; i < ${#arr[@]}; i ++ ))
do
newarr[$index]=${arr[$i]}
(( index ++ ))
done
done
}
$ unset arr newarr
$ newarr[0]=1; newarr[1]=2; newarr[2]=3; newarr[3]=4
$ copy_arrays arr newarr
$ print ${arr[@]}
$ copy_arrays arr2 newarr
$ print ${arr2[@]}
$ unset arr newarr
$ testarr[0]=4; testarr[1]=3; testarr[2]=2; testarr[3]=1
$ copy_arrays arr testarr
$ print ${arr[@]}
4 3 2 1
$ copy_arrays newarr testarr
$ print ${newarr[@]}
4 3 2 1
If I remove the ability to receive multiple arguments from the function, it
works with
any variable:
function copy_array {
# copy_array dest src
#
# Copies src array into dest.
nameref newarr=$1 arr=$2
integer i
for (( i=0; i < ${#arr[@]}; i ++ ))
do
newarr[$i]=${arr[$i]}
done
}
$ unset arr newarr
$ newarr[0]=1; newarr[1]=2; newarr[2]=3; newarr[3]=4
$ copy_array arr newarr
$ print ${arr[@]}
1 2 3 4
$ unset newarr
$ copy_array newarr arr
$ print ${newarr[@]}
1 2 3 4
Now, the man page says this about namerefs (irrelevant information removed):
"A nameref is a variable that is a reference to another variable. A nameref is
created
with the -n attribute of typeset. The value of the variable at the time of the
typeset
command becomes the variable that will be referenced whenever the nameref
variable is
used. If a nameref is used as the index of a for loop, a name reference is
established
for each item in the list."
This says that nameref binding only work when it is declared. If this is true
and type
declarations for local variables can only occur at the start of a function,
then that
leads me to believe there is no way to safely loop over an arbitrary number of
namerefs.
Is this limitation correct?
Thanks,
- Derek Newhall
_______________________________________________
ast-users mailing list
[email protected]
https://mailman.research.att.com/mailman/listinfo/ast-users