Perl300 has asked for the wisdom of the Perl Monks concerning the following question:
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:
Which prints "Hello World". But can I do the same using substr function?#!/usr/bin/perl use strict; use warnings; my $string1 = "Hello"; my $string2 = " World"; $string1 .= $string2; print "$string1\n";
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 | |
|
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 | |
by AnomalousMonk (Archbishop) on Jul 14, 2015 at 18:35 UTC | |
by Perl300 (Friar) on Jul 14, 2015 at 19:02 UTC |