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:56:53 -0500

On Wed, Aug 25, 2021, 9:31 PM hancooper <hancooper@protonmail.com> wrote:

> ‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐
> On Thursday, August 26, 2021 2:02 AM, Dennis Williamson <
> dennistwilliamson@gmail.com> wrote:
>
> > 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.
>
> I am not using an incremented index
>
> (for ((index=1;index<=${#arr[@]});index++)); do)
>
> When I use a sparse indexed array
>
>  a=([0]=x [3]=x [5]=x [8]=x [13]=x)
>  linge-pfa "TITLE" a
>
> the printing is correct
>
> TITLE
> nelm: 5 ${#asta[@]}
> ---
> Key: 0
> Val: x
> ---
> Key: 3
> Val: x
> ---
> Key: 5
> Val: x
> ---
> Key: 8
> Val: x
> ---
> Key: 13
> Val: x
> ---
>
>
>


Right. When I said to keep those things in mind I meant that they are
useful in evaluating whether and why your existing function works - not
that anything was incorrect.

>


reply via email to

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