How to concatenate strings in Perl

A Perl FAQ is "How do you concatenate (merge) two or more strings in Perl?"

Use the "." operator

The short answer is that you use the . operator. Here's a simple example:

$name = "alvin" . " " . "alexander";

Of course I could have also done that like this:

$name = "alvin " . "alexander";

but I wanted to show an example with more than two strings.

Another way

There's another way to do this that's relatively common, especially when you're printing output, like this:

$first_name = "alvin";
$last_name = "alexander";
$full_name = "$first_name $last_name";
print "$full_name\n";

As you can see from the previous example, the two variables are merged together to create the third variable in this line of code:

$full_name = "$first_name $last_name";

In either of these examples, the output would be the same:

alvin alexander

 

Post new comment

The content of this field is kept private and will not be shown publicly.