4

将关联数组作为参数传递给函数以避免重复必须迭代众多关联数组的最佳方法是什么?这样我就可以为函数提供我选择的任何数组来打印。这是我所拥有的:

# Snippet

declare -A weapons=(
  ['Straight Sword']=75
  ['Tainted Dagger']=54
  ['Imperial Sword']=90
  ['Edged Shuriken']=25
)

print_weapons() {
  for i in "${!weapons[@]}"; do
    printf "%s\t%d\n" "$i" "${weapons[$i]}"
  done
}

print_weapons
4

4 回答 4

19

你可以local -n参考

 declare -A weapons=(
 ['Straight Sword']=75
 ['Tainted Dagger']=54
 ['Imperial Sword']=90
 ['Edged Shuriken']=25
 )
 
 print_weapons() {
     local -n array=$1
     for i in "${!array[@]}"; do
         printf "%s\t%d\n" "$i" "${array[$i]}"
     done
 }
 
 print_weapons weapons
于 2015-06-17T14:13:26.040 回答
8

我认为您不能将关联数组作为参数传递给函数。不过,您可以使用以下技巧来解决此问题:

#!/bin/bash

declare -A weapons=(
  ['Straight Sword']=75
  ['Tainted Dagger']=54
  ['Imperial Sword']=90
  ['Edged Shuriken']=25
)

function print_array {
    eval "declare -A arg_array="${1#*=}
    for i in "${!arg_array[@]}"; do
       printf "%s\t%s\n" "$i ==> ${arg_array[$i]}"
    done
}

print_array "$(declare -p weapons)" 

输出

Imperial Sword ==> 90   
Tainted Dagger ==> 54   
Edged Shuriken ==> 25   
Straight Sword ==> 75   
于 2013-07-09T20:46:45.963 回答
2

将变量间接与常规数组一起使用已经够难看的了,使用关联数组很困难——我没有找到遍历键的方法。

我想知道您是否只需要declare -p

print_array() { declare -p $1; }
print_array weapons
declare -A weapons='(["Imperial Sword"]="90" ["Tainted Dagger"]="54" ["Edged Shuriken"]="25" ["Straight Sword"]="75" )'

或者,更漂亮:

print_array() { declare -p $1 | sed 's/[[)]/\n&/g'; }
print_array weapons
declare -A weapons='(
["Imperial Sword"]="90" 
["Tainted Dagger"]="54" 
["Edged Shuriken"]="25" 
["Straight Sword"]="75" 
)'
于 2013-07-09T20:46:15.207 回答
0
#!/bin/bash

   declare -A dict
   
   dict=(
    [ke]="va"
    [ys]="lu"
    [ye]="es" 
   ) 
   
   fun() {
     for i in $@; do
       echo $i
     done
    }
   
   fun ${dict[@]} 

# ||${dict[key]} || ${!dict[@]} || ${dict[$1]} || ${dict[@]}
于 2017-09-06T23:16:57.917 回答