Jump to content

Variable interpolation

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Krauss (talk | contribs) at 09:05, 12 August 2014 (Algorithms). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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]

  1. Replace and exapanding placeholders: creating a new string from original, by find-replace operations.
  2. Split and concat string: splitting the string into an array, and merging it with the corresponding array of values; then join itens by concatenation.

So, it is not a specialized instance of concatenation: is a algorithm, that not is a kind of direct concatenation-algorithm, and that may be not using concatenation operation.

See also

String interpolation

  1. ^ "Enforcing Strict Model-View Separation in Template Engines", T. Parr (2004), WWW2004 conference.
  2. ^ "smallest-template-system/Simplest algorithms", a online tutorial for placeholder-template-systems.