我在 Bash 中玩了一下关联数组,在使用和不使用 声明完全相同的关联数组时发现了以下差异declare
。代码如下:
#!/usr/bin/env bash
echo -e "\n\nASSOCIATIVE ARRAY\n"
declare -A MY_MAP=(
[Madrid]="Spanish"
[London]="English"
[Paris]="French"
[1]=2
[3]=3.14
)
echo "First element: $MY_MAP"
echo "Whole content as single string: ${MY_MAP[*]}"
echo "Whole content quoted separately: ${MY_MAP[@]}"
echo "List of indices: ${!MY_MAP[@]}"
echo "Array length: ${#MY_MAP[*]}"
echo "Array length: ${#MY_MAP[@]}"
echo "Second element: ${MY_MAP[London]}"
echo "Last 2 elements: ${MY_MAP[@]:1:3}"
echo -e "\n\nASSOCIATIVE ARRAY - 2\n"
MY_MAP2=(
[Madrid]="Spanish"
[London]="English"
[Paris]="French"
[1]=2
[3]=3.14
)
echo "First element: $MY_MAP2"
echo "Whole content as single string: ${MY_MAP2[*]}"
echo "Whole content quoted separately: ${MY_MAP2[@]}"
echo "List of indices: ${!MY_MAP2[@]}"
echo "Array length: ${#MY_MAP2[*]}"
echo "Array length: ${#MY_MAP2[@]}"
echo "Second element: ${MY_MAP2[London]}"
echo "Last 2 elements: ${MY_MAP2[@]:1:3}"
当我执行前面的脚本时,我得到以下输出:
ASSOCIATIVE ARRAY
First element:
Whole content as single string: French 3.14 2 English Spanish
Whole content quoted separately: French 3.14 2 English Spanish
List of indices: Paris 3 1 London Madrid
Array length: 5
Array length: 5
Second element: English
Last 2 elements: French 3.14 2
ASSOCIATIVE ARRAY - 2
First element: French
Whole content as single string: French 2 3.14
Whole content quoted separately: French 2 3.14
List of indices: 0 1 3
Array length: 3
Array length: 3
Second element: French
Last 2 elements: 2 3.14
我的问题是declare -A
做什么使输出不同?
如果能详细了解这里发生的事情,我们将不胜感激。
预先非常感谢。
答案1
declare -A
是您的第一个声明被视为关联数组的唯一原因。您的第二个声明将作为索引数组处理。操作索引数组时,索引被视为算术上下文:Madrid
、London
、 和Paris
被解释为变量名,并且由于它们尚未声明,因此它们的值为 0。因此,赋值被读取为[0]="Spanish"
、[0]="English"
、[0]="French"
、[1]=2
、[3]=3.14
和${MY_MAP2[London]}
是${MY_MAP2[0]}
。