What is the perl equivalent of MAX_INT?

一笑奈何 提交于 2019-12-12 10:29:29

问题


I am new to perl and seeking the lowest value in an @array. Is there some constant that represents a very large integer number?

I know I could sort the array and take the beginning, but that seems to be a lot of wasted CPU cycles. What is an elegant solution to my problem in Perl?


回答1:


In the general case, you can use undef to signal a non-existent value; perl scalars aren't restricted to holding just integers. That would be written:

my $min; # undef by default
for my $value (@array) {
  $min = $value if !defined $min or $value < $min;
}

But there are some simpler options here. For example, initialize $min to the first value in the array, then compare to the rest:

my $min = $array[0];
for my $i (1 .. $#array) {
  $min = $array[$i] if $array[$i] < $min;
}

Or just use a built-in function:

use List::Util 'min';
my $min = min @array;



回答2:


To answer you the question you actually asked (even though it's not really of use to you):

  1. Largest integer value that can be stored as a signed integer.

    say ~0 >> 1;
    
  2. Largest integer value that can be stored as an unsigned integer.

    say ~0;
    
  3. All integer values from 0 to this number can be stored without loss as a floating point number.

    use Config qw( %Config );
    say eval($Config{nv_overflows_integers_at});
    

    Note that some larger integers can be stored without loss in a floating point number, but not the one 1 higher than this.




回答3:


9**9**9 works. So does 0+'inf' on many versions/platforms of perl.




回答4:


Perl isn't C; if you try to compute an integer that's too large, you get a floating-point result instead (unless you use bigint, which makes integers unbounded). Beyond that, you get inf.

You can see this with Devel::Peek, which shows you Perl's internal representation of a value:

$ perl -E 'use Devel::Peek; Dump(1000); Dump(1000**100); Dump(1000**100 + 1)'
SV = IV(0xcdf290) at 0xcdf2a0
  REFCNT = 1
  FLAGS = (PADTMP,IOK,READONLY,pIOK)
  IV = 1000
SV = NV(0xd04f20) at 0xcdf258
  REFCNT = 1
  FLAGS = (PADTMP,NOK,READONLY,pNOK)
  NV = 1e+300
SV = NV(0xd04f18) at 0xcdf228
  REFCNT = 1
  FLAGS = (PADTMP,NOK,READONLY,pNOK)
  NV = 1e+300

IV indicates an integer value; NV indicates a floating-point (Number?) value.

You should definitely use a tool suited to your purpose instead of a fuzzy hack; List::Util::min as mentioned in another answer is excellent. Just thought you might like confirmation on your original question :)




回答5:


Here :http://www.perlmonks.org/?node_id=718414

I got an answer that I could verify on linux 64

18,446,744,073,709,551,615 = (2 ^64)-1




回答6:


The biggest integer value perl can store is 9,007,199,254,740,992

I don't know if there's a constant specifically for that.



来源:https://stackoverflow.com/questions/15127989/what-is-the-perl-equivalent-of-max-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!