Variable interpolation
![]() | It has been suggested that this article be merged with Printf format string and String interpolation. (Discuss) Proposed since May 2014. |
In computer programming, variable interpolation (also variable substitution or variable expansion or string interpolation) is the process of evaluating an expression or string literal containing one or more variables, yielding a result in which the variables are replaced with their corresponding values in memory.
Languages that support variable interpolation include Perl, PHP, Ruby, Tcl, Groovy, and most Unix shells. In these languages, variable interpolation only occurs when the string literal is double-quoted, but not when it is single-quoted. The variables are recognized because variables start with a sigil (typically "$
") in these languages.
The programming language provided with variable interpolation must specify when (run time or compile time or other) expansion is performed, because to perform a variable interpolation is equivalent to perform a (simplest) template processing:[1] the string literal is the template, the local variables are inputs, and the variable-references into the string are placeholders.
For example, the following Perl code (which would work identically in PHP):
$name = "Alice";
print "${name} said Hello World to the crowd of people.";
produces the output:
Alice said Hello World to the crowd of people.
Ruby uses the "#
" symbol for interpolation, and allows one to interpolate any expression, not just variables. Other languages may support more advanced interpolation with a special formatting function, such as printf
, in which the first argument, the format, specifies the pattern in which the remaining arguments are substituted.
Algorithms
There are two main types of "expand variable" algoritms for variable interpolation:[2]
- Replace and exapanding placeholders: creating a new string from original, by find-replace operations.
- Split and concat string: splitting the string into an array, and merging it with the corresponding array of values.
So, it is not a specialized instance of concatenation: is a algorithm that can be using concatenation.
See also
- ^ "Enforcing Strict Model-View Separation in Template Engines", T. Parr (2004), WWW2004 conference.
- ^ "smallest-template-system/Simplest algorithms", a online tutorial for placeholder-template-systems.