bug-gawk
[Top][All Lists]
Advanced

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

Re: [bug-gawk] Access variables not conforming to the variable naming co


From: Andrew J. Schorr
Subject: Re: [bug-gawk] Access variables not conforming to the variable naming convention?
Date: Mon, 3 Dec 2018 08:34:05 -0500
User-agent: Mutt/1.5.21 (2010-09-15)

On Sun, Dec 02, 2018 at 11:57:40PM -0700, address@hidden wrote:
> Peng Yu <address@hidden> wrote:
> 
> > > > please don't do that about SYMTAB :)
> > >
> > > Why not? Please give a good reason.
> >
> > A specific example that I have is to parse a headed TSV file and refer
> > to columns by header names (all of these preprocessing are loaded as
> > premade awk files, so users don't need to know $1 $2 any more to refer
> > to columns). Without SYMTAB, it is impossible to do so.
> 
> I was not clear about my intent.  The following continues to work
> as intended:
> 
>       $ ./gawk 'BEGIN { foo = 5
>       > SYMTAB["foo"] += 37
>       > print foo }'
>       42
> 
> Whereas this no longer works as it did previously:
> 
>       $ ./gawk 'BEGIN { foo = 5
>       > SYMTAB["the answer"] = 42
>       > print SYMTAB["the answer"] }'
>       gawk: cmd. line:2: fatal: cannot assign to arbitrary elements of SYMTAB
> 
> So existing code that used SYMTAB to update a variable will continue
> to work.

Hmmm, I think he may have something like this in mind:

bash-4.2$ cat inp
name,age,weight
John,23,150
Hilda,17,110
bash-4.2$ gawk -F, '
> NR == 1 {
>    for (i = 1; i <= NF; i++)
>       SYMTAB[$i] = i
>    next
> }     
> 
> $age >= 20 {
>    print
> }' inp
John,23,150

Are you disabling that ability to create the variable by poking it into SYMTAB
in all cases, or just for invalid identifiers?

Personally, I prefer this approach, which does not depend on the SYMTAB hack
and uses a distinct namespace for the column variables:

bash-4.2$ gawk -F, '
> NR == 1 {
>    for (i = 1; i <= NF; i++)
>       m[$i] = i
>    next
> }
> 
> $m["age"] >= 20 {
>    print
> }' inp
John,23,150

Regards,
Andy



reply via email to

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