You've already got some good answers, but in the spirit of "we've a plethora of ways to do it", you could simply compute the number of "=" signs that you want, and then build a list of them like this:
print defined($count) ? ("=") x (10-$count) : "Undefined count.\n";
Of course, if you calculate the number of "=" symbols you want, then you could also do it as:
print defined($count) ? substr("==========", $count) : "Undefined count.\n";
However, once you try it, you'll notice that your printing is off because you're sometimes putting in a "\n" and sometimes not. If you want to always put in the "\n", you could do it like:
print defined($count) ? ("=") x (10-$count) : "Undefined count.", "\n"; print defined($count) ? substr("==========", $count) : "Undefined count.", "\n";
You could crunch them up into a single line, too:
print defined($count) ? ("=") x (10-$count) : "Undefined count.", "\n" +; print defined($count) ? substr("==========", $count) : "Undefined coun +t.", "\n";
but then it's easy to miss that there are two expressions generating arguments for the print statement and/or easy to confuse the boundary between them.
Sometimes, though, it just simplifies things overall to break things apart a bit. Most of the time, I'd simply do something like:
if (! defined $count) { print "Undefined count.\n" } else { print substr("==========", $count) }
But I do see the natural desire to make the printing front-and-center rather than the conditional logic. I'll frequently do so when the logic is pretty basic:
print "You bought $qty item", $qty>1 ? "s" : "", " today!\n";
But when there's too much logic in formatting something to print, it's often better to do the decisioning earlier, then assemble the bits into your print statement:
my $item = $qty > 1 ? "items" : "item"; my $num = num_to_text($qty); my $when = "today"; $when = "yesterday" if $purchase_date == $yesterday; print "You bought $num $item $when!\n";
Sigh ... I think I'll stop now, or I'll go off on another tangent...
...roboticus
When your only tool is a hammer, all problems look like your thumb.
In reply to Re: Compound statements within the conditional (ternary) operator
by roboticus
in thread Compound statements within the conditional (ternary) operator
by Fendo
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |