Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the perl equivalent of MAX_INT?

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?

like image 406
Zak Avatar asked Feb 28 '13 05:02

Zak


3 Answers

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.

like image 144
ikegami Avatar answered Oct 02 '22 02:10

ikegami


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;
like image 33
hobbs Avatar answered Oct 02 '22 00:10

hobbs


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

like image 20
ysth Avatar answered Oct 02 '22 00:10

ysth