$ perl -E '
my @nums = qw{-1 0 1 9 10 11 19 20 21 23 49 50 51 55};
for my $in (@nums) {
my $out;
if ($in < 10) {
$out = $in;
}
elsif (10 <= $in < 20) {
$out = $in - 2;
}
elsif (20 <= $in < 50) {
$out = $in - 3;
}
else {
$out = $in - 4;
}
printf "IN: %2d OUT: %2d\n", $in, $out;
}
'
IN: -1 OUT: -1
IN: 0 OUT: 0
IN: 1 OUT: 1
IN: 9 OUT: 9
IN: 10 OUT: 8
IN: 11 OUT: 9
IN: 19 OUT: 17
IN: 20 OUT: 17
IN: 21 OUT: 18
IN: 23 OUT: 20
IN: 49 OUT: 46
IN: 50 OUT: 46
IN: 51 OUT: 47
IN: 55 OUT: 51
I've been using that new feature quite a lot.
I believe it makes the definition of ranges, such as are in use here, much clearer and easier to read.
Note all the numbers that I've used for testing.
This checks for edge cases around zero and the numbers where conditions change (as well as your two arbitrary numbers 23 & 55).
This helps to highlight mistakes, as off-by-one errors are common when using <, <=, >= and >:
you should aim to test like this regardless of whatever language or version you might be using.
Your written description only mentions "3 should be subtracted";
however, your code has instances where 2, 3 or 4 are subtracted.
I'll leave you to make adjustments depending on what you really want.
|