help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Function printing arrays


From: Dennis Williamson
Subject: Re: Function printing arrays
Date: Wed, 25 Aug 2021 21:02:19 -0500

On Wed, Aug 25, 2021, 7:45 PM hancooper via <help-bash@gnu.org> wrote:

> I have the following function that prints associative arrays.with key and
> value.
>
> Would like to extend it to print normal arrays (non-associative - without
> keys) as well.
>
> I call it using pfa "TITLE" assoc_array
>
> pfa ()
> {
>
> local _title="$1"
> local -n asta="$2"
>
> local ky="" i=0
> local sga=$(tput setaf 118)
> local sgr=$(tput sgr0)
>
> echo -n $sga ; printf '\n%s\n' "$_title" ; echo -n $sgr
> printf '%s\n' "nelm: ${#asta[@]} \${#asta[@]}"
> printf '%s%s%s\n' $sga "---" $sgr
>
> i=0
> for ky in "${!asta[@]}"; do
> ((i+=1))
> printf 'Key: %s\n' "$ky"
> printf 'Val: %s\n' "${asta[$ky]}"
> if (( i == ${#asc[@]} )); then
> printf '%s%b%s\n\n' "$sga" '-\u2625-' "$sgr"
> else
> printf '%s%s%s\n' "$sga" '---' "$sgr"
> fi
> done
>
> }


I haven't tried your function or really read it very closely, but have you
tried it on indexed arrays?

A couple of things to keep in mind:

Indexed arrays have keys, too. They just happen to be limited to positive
integers

Indexed arrays are sparse. So it's better to iterate over the existing
indices (${!arr[@]}) or elements (${arr[@]}) and not use an incremented
index (for ((index=1;index<=${#arr[@]});index++)); do) because that may
access elements that don't exist and return values that appear to be null.

So your function may work as is.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]