in reply to Perl style: Arguing against three-argument join()
Having worked on a lot of code that does a ton of concatenating of strings (hint: you're soaking in it), I've come to dislike concatenation and much prefer join '', ... or even join "\n", ....
You start out with "you have $count left" and then some refactoring leads to $count being replaced by $new+$old and you have too much sense to do something bizarre like "you have ${\($new+$old)} left" (which doesn't scale well anyway when the strings and expressions grow to the point that more than one line is called for) so the next obvious choice is "you have " . $new+$old . " left" which is, unfortunately, quite wrong. Fixing it starts to give you a hint of how concatenation can suck, "you have " . ($new+$old) . " left". Then somebody makes things fancier and the concatenation needs to be spread over more than one line.
After a lot of experience writing and updating such code, I've come to prefer the following (after trying a lot of alternatives):
$html .= join '', createLink( $USER, "you" ), " have ", $new + $old, " message", 1 == $new+$old ? "" : "s", " left";
So I tend to start out at "you have $count left" then jump next to join '', "you have ", $new+$old, " left".
I've also come to dislike sprintf for such concatenations. I don't like the out-of-order nature between non-format-specifier parts of the first argument and the other items being concatenated into the result. And I don't like the separation between the format specs and the values being formatted. I've also seen too many mistakes like sprintf "bleh $foo%s bar", complex($expr) where $foo might contain a % character. In most cases I find that the majority of the parts are simply being concatenated so if any of the items need 'printf' formatting, then I use sprintf to format just that item:
$html .= join '', createLink( $USER, "you" ), " have a ", sprintf( "%+.2f", $rating ), " rating";
Which might lead to the suggestion of here-docs, which I really dislike since they can't be indented and can fail very confusingly in the face of invisible trailing whitespace.
I hope that leads to some to think of suggesting a "real" templating system. That's often an excellent suggestion. Of course it isn't an appropriate replacement for tons of cases of concatenation. (:
- tye
|
|---|