Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

perl
array
communitycreator

What is array interpolation in Perl 5.3.4?

Hammad Nasir

Interpolation in Perl refers to the process where the respective values replace the variable names. It is commonly used inside double-quoted strings.

Code

The following is an example:

$x = 'Hello';

print "$x World!";

Explanation

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.

Array interpolation

Like scalar variables, array variables can also be interpolated if enclosed inside a double-quoted string.

Code

Example 1

The following is an example of array interpolation.

@myArr = ("Hello", "World", "!");

print "myArr: @myArr";

Explanation

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.

Example 2

Moreover, array interpolation also allows indexing an array. The following example clarifies this:

@myArr = ("Hello", "World", "!");

print "myArr[1]: $myArr[1]";

Explanation

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

perl
array
communitycreator
RELATED COURSES

View all Courses

Keep Exploring