Chain comparisons to avoid excessive typing

Checking that a value is between two others involves two comparisons, and so far in Perl that’s meant that you’ve had to type one of the values more than once. That gets simpler in v5.32 with chained comparisons. This would make Perl one of the few languages that support the feature. So far its implemented in v5.31.10 and until v5.32 is actually released, it isn’t a real feature.


If we all went back to the beginning of programming Perl 6Raku has had this feature for a long time, as has Python (but apparently not JavaScript):

So far you have to write two comparisons and join them with a logical operator. If you’ve never complained about this, you probably haven’t been programming long enough:

if( $lower < $n and $n < $upper ) { ... }

Mathematically, you want to write that as lower < n < upper. It's an idea, not an implementation. A high-level language should allow us to use ideas with the compiler translating it into action. And, that's now what you can do. Write the chained comparison:

use v5.31.10;
if( 1 < $ARGV[0] < 10 ) {
	say "$ARGV[0] is between 1 and 10";
	}
else {
	say "Out of range";
	}

The compiler recognizes the idea and turns it into the right lower level steps:

use v5.31.10;
if( 1 < $ARGV[0] and $ARGV[0] < 10 ) {
	say "$ARGV[0] is between 1 and 10";
	}
else {
	say "Out of range";
	}

And there you have it.

Leave a comment

0 Comments.

Leave a Reply


[ Ctrl + Enter ]