[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [bug-gawk] eval in gawk as a regular command
From: |
Andrew J. Schorr |
Subject: |
Re: [bug-gawk] eval in gawk as a regular command |
Date: |
Sat, 10 Nov 2018 14:30:15 -0500 |
User-agent: |
Mutt/1.5.21 (2010-09-15) |
On Fri, Nov 09, 2018 at 10:48:51PM -0600, Peng Yu wrote:
> > On Wed, Dec 30, 2015 at 07:06:29AM -0600, Peng Yu wrote:
> > > Why not, considering that many other languages have eval? This can
> > > dramatically increase the expression power of a language.
> >
> > In addition to Arnold's points, I think it's worth mentioning that
> > gawk already has the ability to call functions indirectly and the
> > ability to access variables indirectly through the SYMTAB array. So
> > there are already some safer language facilities that allow you
> > to execute code that is a function of the input.
>
> Could you show me some examples of how to mimic some feature of eval()
> using the features that you mentioned? Thanks.
Wow -- I don't think I have ever before received a reply to a message
I sent almost three years ago.
You can consult the manual for documentation and examples. Indirect
function calls are discussed here:
https://www.gnu.org/software/gawk/manual/html_node/Indirect-Calls.html
And there's a cute SYMTAB example here:
https://www.gnu.org/software/gawk/manual/html_node/Auto_002dset.html
The SYMTAB array is more interesting than it looks. Andrew Schorr points out
that it effectively gives awk data pointers. Consider his example:
# Indirect multiply of any variable by amount, return result
function multiply(variable, amount)
{
return SYMTAB[variable] *= amount
}
You would use it like this:
BEGIN {
answer = 10.5
multiply("answer", 4)
print "The answer is", answer
}
When run, this produces:
$ gawk -f answer.awk
-| The answer is 42
With these two capabilities, you have a fair bit of flexibility if you put your
mind to it.
Regards,
Andy