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?
To answer you the question you actually asked (even though it's not really of use to you):
Largest integer value that can be stored as a signed integer.
say ~0 >> 1;
Largest integer value that can be stored as an unsigned integer.
say ~0;
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.
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;
9**9**9
works. So does 0+'inf'
on many versions/platforms of perl.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With