bug-coreutils
[Top][All Lists]
Advanced

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

expr integer format always decimal?


From: Bob Proulx
Subject: expr integer format always decimal?
Date: Fri, 10 Sep 2004 00:22:30 -0600
User-agent: Mutt/1.3.28i

I recently suggested that expr could be used to convert values from
user input or other places to strict decimal form.  And it can
validate non-numberic input easily.  Example:

  expr 08 + 0
  8
  expr foo + 0
  expr: non-numeric argument

However, I can't see anywhere that expr is defined to always read
integers as decimal values.  Where did I miss it?  So using expr is
not a guarentee of behavior.  Is the input format for expr specified
to always be decimal?  I could not find where.

The 'printf' command specifies integer arguments with leading zeros to
be in octal format.  It does so by saying this in SUSv3.

    The argument operands shall be treated as strings if the
    corresponding conversion specifier is b, c, or s ; otherwise, it
    shall be evaluated as a C constant, as described by the ISO C
    standard, ...

And of course C defines this behavior thusly, "A leading 0 (zero) on
an integer constand means octal; a leading 0x or 0X means
hexadecimal."

  printf "%d\n" 08
  bash: printf: 08: invalid number
  0
  printf "%d\n" 010
  8

I guess to use decimal interpretation with possible leading zeros I
must use awk.  SUSv3 says this about awk:

  8. The token NUMBER shall represent a numeric constant. Its form and
     numeric value shall be equivalent to either of the tokens
     floating-constant or integer-constant as specified by the ISO C
     standard, with the following exceptions:

     b. The value of an integer constant beginning with 0 shall be
        taken in decimal rather than octal.

Therefore using awk with leading zeros will reduce them to a decimal
value.  But it is harder to tell if it was non-numeric.  I know I can
always precheck the data.

  awk 'BEGIN{printf "%d\n", 08;}'
  8
  awk 'BEGIN{printf "%d\n", "foo";}'
  0

Bob




reply via email to

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