Jump to content

Variable interpolation

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by 122.182.12.20 (talk) at 07:13, 22 June 2012. 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) 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, 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.

This can really help to reduce the line of codes if coding is done smartly and variables are appropriately used. Assume there are 15 variables test_1, test_2, test_3, ......., test_15 and needs to be initialized as test_1=1, test2=2, ...test_15=15, then it would be a bad coding if 15 lines are written for 15 variables. Here, Interpolation can be used in the best way

for($i=1;$i<=15;$i++)
{
     ${'test_'.$i} = $i;
}

This will create 15 variables. So it all happened in just 3 lines.

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.