On 18/03/2022 17:49, Paul Dragoonis wrote:
Writing code in strings is a DX nightmare


Can you expand a bit on what you mean by that? It seems to be common to assert the opposite, that string interpolation is much more convenient than the alternatives.


Looking around, it seems nearly all currently-popular languages include some form of interpolation.

Notable languages which don't currently support it at all are Java and Go. Rust doesn't have a generic syntax, but some built-in macros support variable-only interpolation: https://blog.rust-lang.org/2022/01/13/Rust-1.58.0.html#captured-identifiers-in-format-strings

Perl, from which PHP has largely inherited its string syntax, is actually more restrictive than most. Arbitrary expressions are just about possible with a bit of hackery, but not really encouraged: https://perldoc.perl.org/perlfaq4#How-do-I-expand-function-calls-in-a-string%3F

All the other languages I looked at have support for full expressions in their interpolation forms:

* C# - $"x + y = {x + y}" - https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated * Dart - 'x + y = ${x + y}' - https://api.dart.dev/stable/2.16.1/dart-core/String-class.html * JavaScript - `x + y = ${x + y}` - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals * Kotlin - "x + y = ${x + y}"  - https://kotlinlang.org/docs/basic-types.html#string-templates
* Python - f'x + y = {x + y}' - https://peps.python.org/pep-0498/
* Raku (Perl6) - "\$x + \$y = { $x + $y }" - https://docs.raku.org/language/quoting.html#Interpolation:_qq * Ruby - "x + y = #{x + y}" - http://ruby-for-beginners.rubymonstas.org/bonus/string_interpolation.html * Scala - s"x + y = ${$x + $y}" - https://docs.scala-lang.org/overviews/core/string-interpolation.html * Swift - "x + y = \(x + y)" - https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html#ID292


Interestingly, a few languages have forms that combine arbitrary expression interpolation with printf-style modifiers. For instance, to format a float x to 3 decimal places, aligned right to width 10:

* C# - $"{x,10:F3}"
* Python - f"{x:10.3}"
* Scala - f"$x%10.3f"

It might be interesting to explore this for PHP, e.g. "{$:$x:10.3f}". If we're not sure we want it yet, we could leave the option open by making anything of the form "{$:expression:format}" a syntax error.

Using a second colon would make ternary expressions slightly awkward; C# handles this by requiring them to be parenthesised, so "{$:( $test ? $x : $y )}" would be valid but "{$:$test ? $x : $y}" would not; we could use some other delimiter, but they'd probably all need something similar.


PS: Reminder to all that convention on this list is to reply below not above quoted text.

--
Rowan Tommins
[IMSoP]

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to