On 2016-10-03, Marc de Bourget <
marcde...@gmail.com> wrote:
> BEGIN {
> #e.g. OPTION_VALUES["--key1"] = 1
> #Test: deliberately uninitialized:
> while ((getline < ARGV[1]) > 0) {
> print $OPTION_VALUES["--key1"]
> }
> close(ARGV[1])
> }
>
> "print $OPTION_VALUES["--key1"]"
> is with the code above the same as "print $0".
> I would have expected at least a warning message.
> Is this a bug or a feature?
$ is an operator in Awk, not a sigil.
Does $(NF - 1) ring a bell?
In the POSIX standard, this grammar production appears:
lvalue : NAME
| NAME '[' expr_list ']'
| '$' expr ;
You can see that $ plays the role of a unary operator, whose
operand is an expr.
The POSIX description of Awk also contains a sentence (just one)
which actually calls it an "operator":
"In the context of the '$' operator, '|' shall behave as if it had a
lower precedence than '$'."
> It seems to be a feature because gawk, mawk, tawk
> behave the same although OPTION_VALUES["--key1"] is not 0.
That's how Awk works: if a number is required somewhere and an
expression is given which refers to something which doesn't exist, or
which refers to an empty string, or a string that contains non-numeric
junk, then, silently, the value zero emerges. (Moreover, there is
usually the side effect that the nonexistent thing pops into
existence.)
If you reject this design as bad, of course you want all such situations
to be diagnosed. Many "well-golfed" Awk one-liners will then trigger
diagnostics.
If you accept this language design, how would you articulate a
rationale for generating a warning for $whatever[index], yet
not generate a warning for uses like counter++ (where counter is never
previously mentioned at all, let alone initialized to zero)?
There are legitimate programs which evaluate $EXPR where EXPR
may refer to a blank, junk or nonexistent array element or variable.
Awk (or an implementation thereof) could benefit from a mode analogous
to the shell's "set -u" which traps *all* accesses to anything
undefined, plus another option which catches all non-numeric junk being
used in an arithmetic context.