Jump to content

String interpolation

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Nadavidson (talk | contribs) at 04:27, 18 February 2011 (added new page for string interpolation). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

String Interpolation is a common feature in many programming languages such as Python, Ruby, PHP, Perl and etc. It means to insert a string or replace a variable with its value.It makes string formatting and specifying contents more intuitive. [1]

Examples

Python

This is the example in python shell:

>>> a, b = 5, 6
>>> print $'a = $a, b = $b'
a = 5, b = 6

PHP

<?php
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;

class foo
{
    var $foo;
    var $bar;

    function foo()
    {
        $this->foo = 'Foo';
        $this->bar = array('Bar1', 'Bar2', 'Bar3');
    }
}

$foo = new foo();
$name = 'Jason';

echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>

The output will be:

My name is "Jason". I am printing some Foo.
Now, I am printing some Bar2.
This should print a capital 'A': A

Perl

#!/usr/bin/perl
use strict;
use warnings;
my $apples = 4;
print "I have $apples apples\n";

The output will be:

I have 4 apples

Security Issues

String Interpolation leads to security problems. When failed to properly escape or filter user input data, system will expose to SQL Injection, Script Injection, XML External Entity Injection (XXE), and Cross Site Scripting (XSS) attacks.[2]