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


In reply to [Solved]: How to append a string at the end of another string using substr by Perl300

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.