Perl300 has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks,

This might be a very foolish thing to ask, but how can I add/append value of $string2 at the end of $string1 and store the resulting string in $string1? I will not know the length of both the strings and might have to repeat this step unknown number of times depending on some conditions. I can use . operator to do it like:

#!/usr/bin/perl use strict; use warnings; my $string1 = "Hello"; my $string2 = " World"; $string1 .= $string2; print "$string1\n";
Which prints "Hello World". But can I do the same using substr function?

I tried same with the code like below, but couldn't figure out a way to insert after the last character of string1. using 0 instead of -1 inserts string2 at the beginning of string1 and -0 does the same.

#!/usr/bin/perl use strict; use warnings; my $string1 = "Hello"; my $string2 = " World"; substr($string1,-1,0,"$string2"); print "$string1\n";

Output of above is: Hell Worldo

Output of same above code when 0 is replaced with 5: Hell World

Thanks in advance!

Note: I am just curious to find out if this can be done using substr but otherwise I am able to get the work done using . operator

Replies are listed 'Best First'.
Re: How to append a string at the end of another string using substr
by toolic (Bishop) on Jul 14, 2015 at 18:16 UTC
    One way (substr):
    use warnings; use strict; my $string1 = "Hello"; my $string2 = " World"; substr $string1, (length $string1), 0, $string2; print "$string1\n"; __END__ Hello World
Re: How to append a string at the end of another string using substr
by 1nickt (Canon) on Jul 14, 2015 at 18:14 UTC

    This works for me:

    Update: if you don't know the length of the string, use  length($string) :-)

    my $string1 = "Hello"; my $string2 = " World"; substr($string1, length($string1), 1, "$string2"); print "$string1\n";
    The way forward always starts with a minimal test.

      Or maybe, since Perl300 is happy to use the concatenation operator:

      c:\@Work\Perl>perl -wMstrict -le "my $string1 = 'Hello'; my $string2 = ' World'; ;; $string1 = substr($string1, 0) . $string2; print qq{'$string1'}; " 'Hello World'


      Give a man a fish:  <%-(-(-(-<

        Thank you: 1nickt, toolic, AnomalousMonk. Your replies work for me. I'll choose one that will suit best for my need.