I'm a Perl beginner and I really love this language, and I was wondering if it was possible to reduce the size of this code, just for fun and so as to learn Perl specificities:
chomp($n=<STDIN>);
if (!$n) {
print 0;
} else {
@t=split/ /,<STDIN>;
foreach $i(0..$n-1) {
$m=$t[$i]if(!$m)||(abs($t[$i])<abs($m))||(($t[$i]==-$m)&&($t[$i]>0));
}
}print $m;
The goal of this code is to give the closest number to 0 of a list , and if there are -4 and 4 for exemple, it will always return the positive number.
$n
is the number of numbers in the list@t
is the list as an array$m
is the min
This is "Temperatures" game on the website Codingame.com.
This code is working pretty well, and I'm trying to reduce its size so as to discover some Perl secrets.
I have some precise questions:
- Is it possible to use a the ternary operator with several instructions in Perl?
- Is is possible to write the
foreach
loop on one line in this case, or even replace theforeach
loop with something else?
I don't really want perfect code as an answer, but some indications, and then I can search details and learn by myself.