3 ms·
Everyone already knows what `if x then y` means, why is there a need for `y if x`? They're both as clear
by iopq 11y ago
Everyone already knows what `if x then y` means, why is there a need for `y if x`? They're both as clear
- raiph 11y agoIf all someone wants to express to a reader is literally `if x then y` then `y if x` doesn't really help. But we typically don't write utterly trivial one-liners with single letter names for conditions and actions. In actual programming there are times when it's more like a series of lines, each of which is something akin to `if some-expression-that's-so-much-longer-than-a-single-letter-that-you-start-to-consider-factoring-it-out-in-to-another-variable-or-function then some-function-or-flow-control`. And when that happens there are times where by far the most important thing a writer wants to first bring to the attention of a reader (eg themselves, later) is some-function-or-flow-control. Sticking with made-up examples for a moment, there's: if long-complex-conditional----that-you-might-start-to-read-thru-in-an-attempt-to-understand-the-code-you're-reading---is-true then blow-rocket-up vs blow-rocket-up if long-complex-conditional----that-you-don't-need-to-read-and-understand-to-understand-that-the-rocket-will-blow-up-if-it's-true----is-true Or it takes me I estimate less than a second to know the gist of the overall control flow of this fragment from a recent Advent of Code entry[1]: next unless (() = /[aeiou]/g) >= 3; next unless /(.)\1/; next if /ab|cd|pq|xy/; $count++; I can immediately see that it increments `$count` unless it bails out of the containing loop (`next`s) due to any of several (complicated looking) conditions. In contrast, it might well take me more than a second to figure that out if they'd written: unless (() = /[aeiou]/g) >= 3 { next } ; unless /(.)\1/ { next }; if /ab|cd|pq|xy/ { next}; $count++; While these examples are pretty weak, I have hope that they might at least give you pause for thought. If you don't see anything going on here worth even thinking about, or more importantly seriously reflecting on, well, at least I tried. And if you're a trained linguist and/or able to quote science to refute what other scientists are finding in recent studies[2], please quote away. :) [1] https://www.reddit.com/r/adventofcode/comments/3viazx/day_5_solutions/cxnt51w https://www.reddit.com/r/adventofcode/comments/3viazx/day_5_... [2] http://www.infosun.fim.uni-passau.de/cl/publications/docs/SKA+14.pdf http://www.infosun.fim.uni-passau.de/cl/publications/docs/SK...
- gluggymug 11y agoIt's actually "if x { y }" in Perl rather than "if x then y". This favours blocks of multiple expressions whereas "y if x" is good for a simple single expression. A lot of the Perl branching and looping directives provide both methods so you can choose what you prefer. Having both ways is great for the Perl one-liners : cat file | perl -e 'while (<>) {next if /^SKIP /; print if /<fancy regex>/;}'