Euphoria
Ticket #1014:
Syntactic Sugar for embedding variables in strings
-
Reported by
euphoric
Nov 16, 2019
Use $aVarName inside strings to act as string embedder.
Instead of this:
integer myInt = 3
string myStr1 = "Your number is " & sprint(myInt) & "."
string myStr2 = sprintf("Your number is %s.",{myInt})
string myStr3 = format("Your number is {1}.",{myInt})
-- etc.
we can do this:
integer myInt = 3
string myStr = "Your number is $myInt."
puts(1,myStr)
Result:
Your number is 3.
Of course, you can use forward-slash to escape the $varName.
integer myInt = 3
string myStr = "Your number is /$myInt."
puts(1,myStr)
Result:
Your number is $myInt.
Details
1. Comment by jimcbrown
Nov 21, 2019
First, the following,
sprintf("Your number is %s.",{myInt})
Does not return "Your number is 3." but it returns "Your number is ?." where ? is a binary character that's typically not displayable.
At run-time, there's no distinction between {49, 50, 51} and "123". So there might be some edge cases where figuring out how to pretty print the variable may have funky results.
In my mind, the bigger issue is backwards compatibility. Using "$" is probably fairly common in strings in Eu code (since it means the dollar sign and is used in reference to money). Using "/$" as an escape isn't so great either, as that's technically part of a valid file path in nix.
Both these objections are overcome if we use a new syntax to declare strings with variables embedded in them. E.g.
sequence s = ~"Your number is $myInt."
Then no backwards compatibility issues arise.