How to concatenate string in Perl

Task. In the program in Perl language there are two variables which contain strings. Need to connect (to concatenate) these two lines in order to get one line.

The solution is to use the operator .

For string concatenation in Perl is used the operator point .. Here is an example code:

▶ Run
#!/usr/bin/perl

my $str1 = 'Hello';
my $str2 = 'world';

print $str1 . $str2;

The program will display the string 'Helloworld'. To make the text read better, you need to concatenate three elements: two variables and one line written in the program code (the so-called "string literal"):

▶ Run
#!/usr/bin/perl

my $str1 = 'Hello';
my $str2 = 'world';

print $str1 . ', ' . $str2;

Concatenation of numbers

The operator . is excellent in that it always treats its arguments as strings. There are programming languages where the concatenation operator is used +, which is also used for adding numbers. Because of this, errors occur that instead of the connection string occurs the operation of addition. In Perl this is not a problem. The operator . is always concatenation, regardless of from the values of the arguments. Therefore, the result of the operation "2" . "2" is exactly the same as the result of the operation 2 . 2, namely, line 22, not number 4.

In addition to the operator . there are other ways how to connect the existing variables to get a new line.

To use interpolation

If the code for a Perl program to create a string using double quotes, variables that written in this line will be replaced by the values of these variables. So to get the same the result as in the previous example, you can use this program:

▶ Run
#!/usr/bin/perl

my $str1 = 'Hello';
my $str2 = 'world';

print "$str1, $str2";

Use sprintf

Another way to combine multiple string values into a string is to use the function sprintf. Here is an example code:

▶ Run
#!/usr/bin/perl

my $str1 = 'Hello';
my $str2 = 'world';

print sprintf('%s, %s', $str1, $str2);

The first argument to the function sprintf a string template, and then transferred items which values will be substituted into the template. This template uses special markers. The simplest token is a text %s, the token tells that instead you just need to substitute value.

Other articles

Comments