bug-gawk
[Top][All Lists]
Advanced

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

Re: [bug-gawk] Postdecrementing $NF


From: Manuel Collado
Subject: Re: [bug-gawk] Postdecrementing $NF
Date: Sun, 08 Sep 2013 20:20:28 +0200
User-agent: Mozilla/5.0 (Windows NT 5.1; rv:17.0) Gecko/17.0 Thunderbird/17.0

El 08/09/2013 20:02, Aharon Robbins escribió:
Hi. You can ignore the mail I just sent.

Date: Sun, 08 Sep 2013 02:56:52 +0200
From: Adam Zieli??ski <address@hidden>
To: address@hidden
Subject: [bug-gawk] Postdecrementing $NF

$NF-- (or even $(NF--) ) - doesn't seem to work as intended.

Instead of giving me a field value and decrementing FN after that, it
converts field value to number and then decrements it.

Doing the same via variable set to NF works perfectly.

I think I see what's going on.  I believe that you've hit on
undefined behavior.  In a test case like:

        echo a b c | gawk '{ print $(NF--) }'

You are assuming that gawk does (or "should do") things in this order:

        1. Get the value of NF, save it
        2. Use the saved value to fetch the field at $NF
        3. Decrement NF at some point
        4. Print the field value

Gawk is actually doing the following:

        1'. Get the value of NF, save it
        2'. Decrement NF
        3'. Use the saved value to fetch the field at $NF
        4'. Print the field fetched using the saved value

The reason this does not work as you expect is that decrementing NF
reduces the number of available fields.  Thus when gawk executes step
3', there is no data there, because gawk has already thrown away the
original value that was there.

I don't believe that one behavior is more "correct" than the other;
of four different awks that I tested, including gawk, two do it the
one way, and two do it the other.

The second behavior is probably the "correct" one. It it dubious to use the value of a parenthesized subexpression before fully evaluating it.

The real undefined behavior issue is if decrementing NF should in fact drop the last field, I.e., if decrementing the read-only NF variable should affect the access to the original fields, or just modify a local user visible copy of NF.

Regards,

--
Manuel Collado - http://lml.ls.fi.upm.es/~mcollado




reply via email to

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