in reply to Different way to use while loop

This

  1 while s/^FOO/BAR/g;

repeats the substitution till it fails¹ ...

...which doesn't make much sense because of the ^ anchoring at the start, i.e. it can't substitute more than once.

This should lead to the same results

while (<FH>) { s/^FOO/BAR/; print "$_"; }

The rest (iterating over lines from filehandle with $_) should be obvious, right?

If not have a look at perlintro

Cheers Rolf

PS: Je suis Charlie!

update
¹) it's a postfix equivalent of

while (s/^FOO/BAR/g) { 1 ; # no op }

Replies are listed 'Best First'.
Re^2: Different way to use while loop
by Anonymous Monk on Jan 09, 2015 at 03:48 UTC

    repeats the substitution till it fails ...

    What kind of substitution is it?

    Its a global substitution, so even if it was  s/FOO/BAR/g there would be no need to repeat that, the global substitution took care of it in one pass

      > the global substitution took care of it in one pass

      not in scalar context which is enforced by the boolean context of the while condition.

      see s///g in perlop, perlre , perlretut

      Cheers Rolf

      PS: Je suis Charlie!

      update
      Global matching

      In scalar context, successive invocations against a string will have //g jump from match to match, keeping track of position in the string as it goes along. You can get or set the position with the pos() function.

      update

      I was wrong the scalar thing is only valid for m//g , s///g just returns the number of all substitutions

      DB<112> $_ = "a a a" => "a a a" DB<113> scalar s/a/x/g => 3

      update

      See this example in perlop for a similar use case

      1 while s/(\d)(\d\d\d)(?!\d)/$1,$2/g;

      But without knowing Foo and Bar we can only speculate.

      Its a global substitution, so even if it was s/FOO/BAR/g there would be no need to repeat that, the global substitution took care of it in one pass
      Not necessarily:
      $ perl -E '$_ = "caattt"; s/at//g; say' catt $ perl -E '$_ = "caattt"; 1 while s/at//g; say' ct
      Without knowing FOO and BAR, we can't say whether new instances of FOO might be created in the string when the substitution is performed.