传递关联数组与巴什参数 [英] Passing associative array as argument with Bash
本文介绍了传递关联数组与巴什参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是传递一个关联数组作为参数传递给函数以避免遍历众多准阵列的重复的最好方法?这样我可以给我的功能选择要打印的任何数组。下面是我有:
#片段声明-A武器=(
['直剑'] = 75
['污点匕首'] = 54
['尚方宝剑'] = 90
['边飞镖'] = 25
)print_weapons(){
因为我在$ {武器[@]!};做
printf的%S \\ t%d个\\ N$ I$ {武器[$ i]}
DONE
}print_weapons
解决方案
我不认为你可以通过关联数组作为参数传递给函数。您可以使用下面的技巧来解决,虽然这个问题:
#!/斌/庆典声明-A武器=(
['直剑'] = 75
['污点匕首'] = 54
['尚方宝剑'] = 90
['边飞镖'] = 25
)功能print_array {
EVAL声明-A arg_array =$ {1#* =}
因为我在$ {!arg_array [@]};做
printf的%S \\ t%S \\ n$ I ==> $ {arg_array [$ i]}
DONE
}print_array$(申报-p武器)
输出
尚方宝剑==> 90
被感染的匕首==> 54
边飞镖==> 25
平直的剑==> 75
What's the best way to pass an associative array as an argument to a function to avoid the repetition of having to iterate over numerous associate arrays? That way I can give the function any array of my choice to print. Here's what I have:
# 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
解决方案
I don't think you can pass associative arrays as an argument to a function. You can use the following hack to get around the problem though:
#!/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)"
Output
Imperial Sword ==> 90
Tainted Dagger ==> 54
Edged Shuriken ==> 25
Straight Sword ==> 75
这篇关于传递关联数组与巴什参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文