bug-gawk
[Top][All Lists]

## Re: [bug-gawk] How to mimic inserting an element to a vector?

 From: arnold Subject: Re: [bug-gawk] How to mimic inserting an element to a vector? Date: Fri, 12 Jul 2019 03:55:24 -0600 User-agent: Heirloom mailx 12.5 7/5/10

```There is no standard function for getting the length of an array.
That the builtin function works is a gawk extension, described in the
manual where length() is described.

Arnold

> I thought there ought to be a function like length for arrays, but the
> manual (Hint, hint!) doesn't mention it in the array section, and I've
> learned it in the early days.
> -E
>
> On Thu, 11 Jul 2019 at 20:35, <address@hidden> wrote:
>
> > Your way seems to work. I would probably write it like this
> > (untested):
> >
> > function insert(a, ind, val,    i, l)
> > {
> >         l = length(a)
> >         for (i = l; i >= ind; i--)
> >                 a[i+1] = a[i]
> >
> >         a[ind] = val
> > }
> >
> > Arnold
> >
> > Peng Yu <address@hidden> wrote:
> >
> > > Hi,
> > >
> > > I use the following code to mimic inserting an element to a vector
> > > (i.e, the keys are 1,2,...). But it is a little cumbersome. Is there
> > > any implement that is better?
> > >
> > > function insert(a, i, v) {
> > >   for(k in a) {
> > >     if(k>=i) {
> > >       a[k+1] = a[k]
> > >     }
> > >   }
> > >   a[i] = v
> > > }
> > >
> > > BEGIN {
> > >   for(i=1;i<=3;++i) {
> > >     a[i] = 100 + i
> > >   }
> > >   PROCINFO["sorted_in"] = "@ind_num_desc"
> > >   insert(a, 2, 2)
> > >
> > >   PROCINFO["sorted_in"] = "@ind_num_asc"
> > >   for(k in a) {
> > >     print k, a[k]
> > >   }
> > > }
> > >
> > > --
> > > Regards,
> > > Peng
> >
> >
> >

```