Perl string FAQ: How do I concatenate Perl strings?
When you work with Perl, you're often working with strings, and you’ll very often you need to concatenate strings. For instance, I recently had a need to create a temporary filename, and wanted to use the original filename as part of the temporary name.
I was going to get the first part of the filename (the filename prefix) by calling a function that generated temporary filenames. After getting the first part of the filename, I wanted to prepend the directory "/tmp/
" to the beginning of the name, and append the filename extension ".tmp
" to the end of the name. Here's how I did it.
Perl string concatenation, Solution #1: Using ${name}
One of the best and simplest ways to concatenate Perl strings is with this syntax:
$name = 'foo'; $filename = "/tmp/${name}.tmp";
In this example, I have a Perl string variable named $name
that contains the text "foo
", and I use this Perl syntax to embed the value of that variable in the string that I'm assigning to the new variable $filename
. This example prepends the string '/tmp/
' to the variable $name, and appends the '.tmp
' filename extension to $name
.
These days I use this Perl string concatenation approach more than any other.
Perl string concatenation, Solution #2: Using Perl's dot operator
Another way to concatenate Perl strings is to use the "dot" operator (i.e., the decimal character). In some circumstances it can make your Perl script easier to read than the syntax shown above.
To concatenate Perl strings this way, just place the dot operator in between the strings you want to merge on the right side of the '=' symbol in your statement, as shown here:
$name = checkbook'; $filename = '/tmp/' . $name . '.tmp'; # $filename now contains "/tmp/checkbook.tmp"
Again, this example creates a Perl variable named $filename that contains the concatenated string contents shown on the right side of that statement.
Perl string concatenation, Solution #3: Using Perl's join function
Another way to create the desired variable $filename
is to use the Perl join function. With the join
function you can merge as many Perl strings together as you like, and you can specify what token you want to use to separate each string.
The code shown in Listing 2 below uses the Perl join function to achieve the same result as the code shown in Listing 1:
$name = 'checkbook'; $filename = join '', '/tmp/', $name, '.tmp'; # $filename now contains "/tmp/checkbook.tmp"
I rarely use the Perl join function to merge simple strings like this, but I thought I'd show this as another possible way to concatenate Perl strings.
Perl string concatenation: Summary
I hope these Perl string concatenation examples have been helpful. I just updated this article in 2011 to update it to the current Perl "best practices".