No, as you suspect, s/// doesn't work like that.

How about something like:

use strict; use warnings; my (@config); push @config, 'line 1 oldtext appears but once here', 'line 2 oldtext is here twice oldtext', 'line 3 oldtext is here oldtext three oldtext times!'; for (@config) { my $count = 2; while ($count-- && s/oldtext/newtext/) { print 'Replaced '} print "\n"; } print "$_\n" for @config;

Output:

Replaced Replaced Replaced Replaced Replaced line 1 newtext appears but once here line 2 newtext is here twice newtext line 3 newtext is here newtext three oldtext times!

Update -- some explanation:

The print statement in the while loop is to provide a hint about how this works. We're taking advantage of a couple facts here: (1) s/.../.../ will only perform 1 substitution at a time, and (2) s/.../.../ returns the number of substitutions it performed (either 0 or 1 in this case). I set $count to the maximum number of replacements I want to make.

For the first line of the array, the while loop runs only once. Even though $count at that point is 1, the s/// returns 0, and that makes the while condition false.

For the second and third lines of the array, the loop runs only twice, and that's because $count has counted down to 0.

But God demonstrates His own love toward us, in that while we were yet sinners, Christ died for us. Romans 5:8 (NASB)


In reply to Re^3: String substitution inside an array by GotToBTru
in thread Re^2: String substitution inside an array by dhawal.mahajan

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.