开发者

Perl long data type

I am writing an app in Perl that requires开发者_开发问答 long data type instead of integers. How can I achieve this. For example;

my $num = sprintf('%ld', 27823221234);

print $num;

The output is not a long, but an integer.


Your options are:

  • use a perl compiled for 64 bits
  • use Math::Int64
  • use Math::BigInt

update: ah, you can also use floats instead of integers:

printf("%.0f", 2**50)

IIRC, on most current architectures, floats can represent integers up to 2**54-1 precisely.


Here is some code that illustrates some of how Perl behaves - derived from your example:

use strict;
use warnings;

my $num = sprintf("%ld", 27823221234);
print "$num\n";

my $val = 27823221234;
my $str = sprintf("%ld", $val);
printf "%d = %ld = %f = %s\n", $val, $val, $val, $val;
printf "%d = %ld = %f = %s\n", $str, $str, $str, $str;

With a 64-bit Perl, this yields:

27823221234
27823221234 = 27823221234 = 27823221234.000000 = 27823221234
27823221234 = 27823221234 = 27823221234.000000 = 27823221234

If you really need big number (hundreds of digits), then look into the modules that support them. For example:

  • Math::BigInt


You are probably confused. Perl natively supports "long"-sized integer math, but I don't think its internal representation is where your problem is. What are you expecting your output to look like?


in your case 27823221234 is really represented as double, so when you try to feed to to sprintf you receive -1

my $x = 27823221234;

my $num = sprintf('%lf', $x);

print $num, "\n";

yields to

27823221234.000000

if you want to do math operations with large integers, consider using Math::Bigint module.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜