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?
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;