- publishing free software manuals
Perl Language Reference Manual
by Larry Wall and others
Paperback (6"x9"), 724 pages
ISBN 9781906966027
RRP £29.95 ($39.95)

Sales of this book support The Perl Foundation! Get a printed copy>>>

6.3 Flavors of Perl numeric operations

Perl operations which take a numeric argument treat that argument in one of four different ways: they may force it to one of the integer/floating/ string formats, or they may behave differently depending on the format of the operand. Forcing a numeric value to a particular format does not change the number stored in the value.

All the operators which need an argument in the integer format treat the argument as in modular arithmetic, e.g., mod 2**32 on a 32-bit architecture. sprintf "%u", -1 therefore provides the same result as sprintf "%u", ~0.

Arithmetic operators
The binary operators + - * / % == != > < >= <= and the unary operators - abs and -- will attempt to convert arguments to integers. If both conversions are possible without loss of precision, and the operation can be performed without loss of precision then the integer result is used. Otherwise arguments are converted to floating point format and the floating point result is used. The caching of conversions (as described above) means that the integer conversion does not throw away fractional parts on floating point numbers.
++
++ behaves as the other operators above, except that if it is a string matching the format /^[a-zA-Z]*[0-9]*\z/ the string increment described in 7 is used.
Arithmetic operators during use integer
In scopes where use integer; is in force, nearly all the operators listed above will force their argument(s) into integer format, and return an integer result. The exceptions, abs, ++ and --, do not change their behavior with use integer;
Other mathematical operators
Operators such as **, sin and exp force arguments to floating point format.
Bitwise operators
Arguments are forced into the integer format if not strings.
Bitwise operators during use integer
forces arguments to integer format. Also shift operations internally use signed integers rather than the default unsigned.
Operators which expect an integer
force the argument into the integer format. This is applicable to the third and fourth arguments of sysread, for example.
Operators which expect a string
force the argument into the string format. For example, this is applicable to printf "%s", $value.

Though forcing an argument into a particular form does not change the stored number, Perl remembers the result of such conversions. In particular, though the first such conversion may be time-consuming, repeated operations will not need to redo the conversion.

ISBN 9781906966027Perl Language Reference ManualSee the print edition