Interpolation in Perl refers to the process where the respective values replace the variable names. It is commonly used inside double-quoted strings.
The following is an example:
$x = 'Hello'; print "$x World!";
In the example above, a scalar variable x
is declared that contains the string Hello
. The string $x World!
is provided as an argument to the print
method. Since the string is in double-quotes, the variable x
is replaced by its value.
Like scalar variables, array variables can also be interpolated if enclosed inside a double-quoted string.
The following is an example of array interpolation.
@myArr = ("Hello", "World", "!"); print "myArr: @myArr";
In the example above, the array variable myArr
contains three string elements printed out on the screen via array interpolation. Notice that space is introduced between elements but not at the start or the end.
Moreover, array interpolation also allows indexing an array. The following example clarifies this:
@myArr = ("Hello", "World", "!"); print "myArr[1]: $myArr[1]";
In the example above, the array variable myArr
contains three string elements. We only print the second element World
here by indexing the array variable. Notice that we used the $
sign instead of the @
sign before the variable name.
RELATED TAGS
CONTRIBUTOR
View all Courses