Perl Concatenate: Joining Strings and Arrays in Perl

Concatenating Strings In Perl



Concatenating strings in Perl is easy. The only thing to remember is that you have to use the dot operator, not +:

my $string1 = "Nice";
my $string2 = "weather";
my $string3 = "today";

my $string4 = $string1 . ' ' . $string2 . ' ' . $string3;

print $string4;




Nice weather today




Here we've concatenated three strings together with some strings containing empty space for visibility.



Printing (Displaying) Concatenated Strings in Perl



If don't want to store the concatenated string but just print it out onscreen, you can of course use print() directly:

my $string1 = "cat";
my $string2 = "fish";

print $string1 . $string2;




catfish




Some interesting variations are possible using print(). The print() function will print any number of arguments passed to it, so instead of concatenating multiple strings we could simply pass them to print() as separate arguments.

my $string1 = "cat";
my $string2 = "fish";

print $string1, $string2;




catfish




Yet another alternative that often helps to create beautifully clear, legible code, is rather than concatenate strings -- embed them in a bigger string. An example should make things clear.

my $user = "Frank";
my $fruit = "tangerine";

print "Hello $user, would you like a $fruit?n";




Hello Frank, would you like a tangerine?





... and of course there's nothing to stop you mixing up all these alternatives together.

Concatenating Arrays in Perl



To concatenate arrays in Perl, you need a different approach. Use the built-in push() function to add one array to the end of another.

my @array1 = ("one", "two");

my @array2 = ("three", "four", "five");

push @array1, @array2;

foreach my $combined(@array1) {
    print "$combinedn";
}




one
two
three
four
five