my $number = $logical_test ? $value : 0;
or
my $number = $value;
$number = 0 unless $logical_test;
or
my $number = 0;
$number = $value if $logical_test;
depending whether I want to stress the default value of $number. (I might use one of the latter two if $logical_test is expected to have a particular value, and it not having it is an exception, I use the former line if $logical_test could go both ways).
If $logical_test is 0 if it's false, I might even write it as:
my $number = $logical_test && $value;
I wouldn't easily write:
my $number;
if ($logical_test) {
$number = $value;
}
else {
$number = 0;
}
as it assigns an initial value to $number in a different scope than its declaration - IMO, that doesn't score bonus points when it comes to readability. It's also 7 lines instead of 1, although it can easily be shortened to:
my $number;
if ($logical_test) {$number = $value}
else {$number = 0}
But still, it's three lines. And worse, both blocks have two thirds of their tokens in common - which just shouts "factor out, factor out". Which would lead to:
my $number = do {if ($logical_test) {$value} else {0}};
But then I prefer:
my $number = $logical_test ? $value : 0;
|