http://qs321.pair.com?node_id=32418

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question: (strings)

How do I concatenate a string?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I concatenate a string?
by davido (Cardinal) on Sep 14, 2003 at 02:49 UTC
    For simple concatenation,

    my $foo = "Foo"; my $bar = "Bar"; my $string = $foo . $bar; # $string contains "FooBar".

    For concatenating the new string to the end of the existing string (appending):

    my $foo = "Foo"; my $bar = "Bar"; $foo .= $bar; # $foo now contains "FooBar"

    For concatenating multiple strings all at once, use join. Join is (according to the Camel book) the most efficient way to concatenate many strings together. Join can be used with a delimiter, or with a null string as the delimiter, so that nothing is inserted between the strings that are joined (concatenated) together.

    my $this = "This"; my $that = "That"; my $the = "The"; my $other = "Other"; my $string = join "", $this, $that, $the, $other; # $string now contains "ThisThatTheOther".

    Join can do a lot more than just simple concatenation. Whatever you put between the quotes will be inserted between the strings that are being joined together. Also, join can accept not just a list of scalar variables, but also an array, or a list of literal strings.

Re: How do I concatenate a string?
by ar0n (Priest) on Sep 14, 2000 at 10:37 UTC
    As merlyn so eloquently put it ;), use the '.' operator:
    my $foo = "Foo"; my $bar = "Bar"; my $str = $foo . $bar; print $str;
    Which of course will print "FooBar".

    Originally posted as a Categorized Answer.

Re: How do I concatenate a string?
by jupiter2005ster (Initiate) on Oct 09, 2014 at 20:46 UTC
    my $foo = "Foo"; my $bar = "Bar"; my $foo .= $bar;
    this is incorrect. the third row doesn't need 'my' so it needs to look like:
    $foo .= $bar;

    Originally posted as a Categorized Answer.

Re: How do I concatenate a string?
by toolic (Bishop) on Aug 20, 2009 at 23:54 UTC
    Interpolation using double quotes, for example, (see Quote and Quote like Operators) can be used to concatenate 2 (or more) scalar variables into a 3rd scalar variable:
    my $s1 = 'Perl'; my $s2 = 'Monks'; my $s3 = "$s1$s2"; print "$s3\n"; # $s3 contains 'PerlMonks'

    or using this syntax:

    my $s3 = "${s1}${s2}";

    Interpolation of array variables can also be performed to concatenate all element of the array into a string. It is necessary to unset the LIST_SEPARATOR ($") special variable, and it is good practice to localize this change to its own block:

    { undef $"; my @strs = 'a' .. 'e'; my $s4 = "@strs"; print "$s4\n"; # $s4 contains 'abcde' }
Re: How do I concatenate a string?
by Anonymous Monk on Jun 01, 2003 at 18:53 UTC
    How do I concatenate $x copies of string my $foo?

    Originally posted as a Categorized Answer.