Friday, August 10, 2007

How to concatenate strings with Perl

Many times when you're working with Perl you're working with strings. Oftentimes you need to concatenate strings. For instance, I recently had a need to create a temporary filename.

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. "How can I do this easily?", I thought.

Method #1 - using Perl's dot operator

Concatenating strings in Perl is very easy. There are at least two ways to do it easily. One way to do it - the way I normally do it - is to use the "dot" operator (i.e., the decimal character).

The simple example shown below demonstrates how you can use the dot operator to merge, or concatenate, strings. For simplicity in this example, assume that the variable $name is assigned the value "checkbook". Next, you want to pre-pend the directory "/tmp" to the beginning of the filename, and the filename extension ".tmp" to the end of $name. Here's the code that creates the variable $filename:

$name = "checkbook";
$filename = "/tmp/" . $name . ".tmp";

#----------------------------------------------#
# $filename now contains "/tmp/checkbook.tmp" #
#----------------------------------------------#

Listing 1: Concatenating strings with the dot operator.


Method #2 - using Perl's join function

A second way to create the desired variable $filename is to use the join function. With the join function, you can merge as many 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 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" #
#----------------------------------------------#

No comments: