Variable interpolation

From Wikipedia, the free encyclopedia
Jump to: navigation, search

In computer programming, variable interpolation (also variable substitution or variable expansion) 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. It is a specialized instance of concatenation.

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.

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.

See also[edit]

String interpolation