Perl Monk, Perl Meditation PerlMonks

### Re: Ternary vs. Sort vs. Max

by shmem (Chancellor)
 on Aug 10, 2015 at 10:31 UTC ( #1138001=note: print w/replies, xml ) Need Help??

in reply to Ternary vs. Sort vs. Max

Just for the sake of TIMTOWTDI:

```\$max = (\$x,\$y)[\$x<\$y];
\$min = (\$x,\$y)[\$x>\$y];

which is a golfed version of your 2nd variant: (sort-of) a one-step sort which eliminates building a code block frame and the call of sort. Ternary is cheaper, since it doesn't involve bulding a list.

update:
I've been working at a place where restrictive coding standards prohibited ternary and forced me to write

```if (\$x < \$y ) {
\$max = \$y;
}
else {
\$max = \$x;
}

- which is as cheap as ternary (I guess) but looks convoluted to me - among other hilarities. Good riddance.

perl -le'print map{pack c,(\$-++?1:13)+ord}split//,ESEL'

Replies are listed 'Best First'.
Re^2: Ternary vs. Sort vs. Max
by fullermd (Priest) on Aug 11, 2015 at 04:25 UTC
```if (\$x < \$y ) {
\$max = \$y;
}
else {
\$max = \$x;
}

When faced with the need to write a similar construct (e.g., the condition is too long to make an easily scannable ternary or the like), I find it easier to Just Pick One and then write one conditional, like

```\$max = \$x;
if(\$x < \$y) {
\$max = \$y;
}

Aside from shorter, I find it actually more descriptive, especially if the other side is an else rather than elseif; "x except when y" as a description reads just like the code.

Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1138001]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2021-09-27 20:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?

No recent polls found

Notices?