Home > Enterprise >  How to iterate over array of associated arrays in zsh
How to iterate over array of associated arrays in zsh

Time:09-23

Here is an example that runs how I want it to in bash

declare -A price_oracle=(
  [name]="price_oracle_name"
  [active]=true
)

declare -A market=(
  [name]="market_name"
  [active]=true
)

declare -a contract_list=(
  price_oracle
  market
)

for contract in "${contract_list[@]}"; do
  declare -n lst="$contract"
  if ${lst[is_active]}; then
    echo "Importing schema for $contract contract"
    wasm-cli import -s --name $contract contracts/$contract/schema
  fi
done

How can this same functionality be accomplished in zsh? declare -n is not valid in zsh.

CodePudding user response:

The nested parameter expansion flag (P) can be used instead of a bash nameref:

#!/usr/bin/env zsh

declare -A price_oracle=(
  [name]=price_oracle_name
  [active]=true
)

declare -A market=(
  [name]=market_name
  [active]=true
)

declare -a contract_list=(
  price_oracle
  market
)

for contract in $contract_list; do
  local -A lst=("${(Pkv@)contract}")
  if ${lst[active]}; then
    echo "Importing schema for $contract contract"
    wasm-cli import -s --name ${lst[name]} contracts/$contract/schema
  fi
done

To work with the associative array, this also uses the key (k), value (v), and array separation (@) expansion flags. These are described in the zshexpn man page and the online zsh documentation.

  • Related