1836984 Members
1976 Online
110111 Solutions
New Discussion

awk bug or feature?

 
SOLVED
Go to solution
Gord Moore
Frequent Advisor

awk bug or feature?

I know squat about awk. A user sent me a note saying he thinks there is a bug that needs a patch.

This is what he wrote. Hopefully I get the punctuation right.

In the awk code:
HOUR = substr($3,1,2)
if (HOUR>=8 && HOUR < 18) {
... code for prime shift
}
The test was always failing, regardless of the assignment to HOUR. It looks like the problem is in the character to integer comparison. I corrected the script with a single line:
HOUR = substr($3,1,2)
HOUR = HOUR + 0
if (HOUR ....

He says that the script works and was wondering if there was a patch that I should throw on.

What should I tell him? Is the script doing what it should? Is this a bug? Is there a better way to code it?

Thanks.

3 REPLIES 3
Solution

Re: awk bug or feature?

substr returns a string and not a number which ends up foiling some of the "automatic" conversions that take place in awk. This is not really a bug in awk, but a type of logic error in the script.

Your solution of adding "0" to the variable is fine, or you could use something like:

HOUR = int(substr($3, 1, 2))

instead which forces HOUR to be an integer.

Regards,

Rich
A. Clay Stephenson
Acclaimed Contributor

Re: awk bug or feature?

Awk is working as it should. It is up to the programmer to force numeric context. Substr() is a string function. The 'trick' is to change
HOUR = substr($3,1,2)
to
HOUR = substr($3,1,2) + 0

This will coerce HOUR into numeric context and all will then be well. Sometimes the reverse problem must be dealt with as well to force string context; the 'trick' in that case is to append a null string to a value. Both of these are stand awk idioms and well-disciplined awk programers will always use the '+ 0' to avoid those situations where one's code works (or doesn't work) by accident.

If one doesn't force context, one will find cases where identical awk code will behave differently on different platforms.
If it ain't broke, I can fix that.
Rodney Hills
Honored Contributor

Re: awk bug or feature?

Gord,

Of course there is a patch for "awk".

It's called "perl" :-)

-- Rod Hills
There be dragons...