dhawal.mahajan has asked for the wisdom of the Perl Monks concerning the following question:

I am a beginner in Perl and am trying to construct a script which can replace the occurrences of a particular string in an array some fixed number of times. The no. of times is stored in a variable $count. So when I tried above methodology using a slight modification : s/oldtext/newtext/$count for @config;, I got a Perl syntax error. I know this is very naive, but my thinking was that if /g at the end makes this substitution for all the occurrences of oldtext, then /$count at the end should replace the oldtext by newtext by $count no. of times! Do I have to construct a loop by reading the array @config line by line and then replace $count number of times? Actually how do I construct such a loop?
  • Comment on Re^2: String substitution inside an array

Replies are listed 'Best First'.
Re^3: String substitution inside an array
by GotToBTru (Prior) on Jan 25, 2016 at 20:20 UTC

    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)