Estou brincando um pouco com arrays associativos no Bash e encontrei a seguinte diferença ao declarar exatamente o mesmo array associativo com e sem declare
. O código é o seguinte:
#!/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}"
Quando executo o script anterior, obtenho a seguinte saída:
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
Minha pergunta é o que está declare -A
fazendo que torna a saída diferente?
Uma visão detalhada do que está acontecendo aqui será apreciada.
Muito obrigado antecipadamente.