in reply to Compound statements within the conditional (ternary) operator

Fendo:

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.

Replies are listed 'Best First'.
Re^2: Compound statements within the conditional (ternary) operator
by AnomalousMonk (Archbishop) on Apr 14, 2018 at 23:48 UTC

    A minor nit: I don't know about other Englishes, but for Yank-Canuck and I think Brit English usage, I would construct the plural slightly differently:

    c:\@Work\Perl\monks>perl -wMstrict -le "for my $qty (0 .. 3) { printf qq{you bought $qty item%s today \n}, $qty == 1 ? '' : 's'; } " you bought 0 items today you bought 1 item today you bought 2 items today you bought 3 items today


    Give a man a fish:  <%-{-{-{-<

      AnomalousMonk:

      Yep, if $qty kan be naught, then yer code would be more Englishy. ;^)

      ...roboticus

      When your only tool is a hammer, all problems look like your thumb.