Well, for equality testing, I'd use a hash (or array for dense numerical indexes) lookup.
my @COLORS = qw( white red blue green yellow );
return exists $COLORS[$i] ? $COLORS[$i] : $COLORS[0];
But if you need logical checks that are more complex than equality, the ternary chain you show is quite handy:
return $i < 5 ? 'red'
: $i < 20 ? 'blue'
: $i%3 == 0 ? 'green'
: $i%5 == 0 ? 'yellow'
: 'white';
And you are absolutely correct about the importance of formatting with this construct.
As for the trailing 'if','unless' and 'or', formatting is key here as well. I tend to bring those onto a separate line:
print "This is my very long string that I wish to print out to display
+ my message on the screen but only when I want it too!"
if $i == 1;
# the very common 'or die' idiom with a big brutish open()
open (
my $filehandlewithalongname,
$modevariablewithalongname,
$pathvariablewithalongname
) or die "Unable to open file $pathvariablewithalongname: $!\n";
# 'or die' again with a smaller, kinder open:
open ( my $fh, $mode, $path )
or die "Unable to open $path: $!\n";
# is equivalent to this 'die unless'
# which I have never seen used with open().
die "Unable to open $path: $!\n"
unless open ( my $fh, $mode, $path )
# however, 'die unless' is common with value checks.
die "Illegal value: $rotifer\n"
unless $rotifer =~ /^is ok$/;
# as is 'die if'
die "Illegal value: $rotifer\n"
if $rotifer =~ /^is not ok$/;
I think the main difference between 'x or y' and the equivalent 'y unless x' is emphasis. In the former, the emphasis is on the statement 'x'. Whereas in the latter, the emphasis is on the statement 'y'. Choice of form is therefore indicated by what you believe will express your intent most clearly.
Another thing worth noting here is that one can use 'x and y' as a stand-in for 'y if x'. I avoid 'x and y' because the short circuit evaluation of 'and' is, in my opinion, not intuitive. If I want to emphasize the 'x' in the code, I just use the good old 'if(x) { y }' form instead of 'x and y'.
|