in reply to Finding the positions of a character in a string

(From the CB where L~R was discussing this) Using index:

perl -le "my $str=qq(\n--\n--\n); my $p=0; do { $p=index($str,qq(\n),$ +p); print $p++; } while $p>0;"

And using s///.

perl -le "my $str=qq(\n--\n--\n); $str=~s/\n/print $-[0]; '\n'/ge;
---
$world=~s/war/peace/g

Replies are listed 'Best First'.
Re^2: Finding the positions of a character in a string
by sauoq (Abbot) on Nov 28, 2005 at 16:17 UTC
    And using s///.

    Ewww.

    print pos($str)-1 while $str =~ /\n/g; print $-[0] while $str =~ /\n/g;

    Update: Oops, need to subtract 1 from pos() or use $-[0] as you did in the s/// version.

    -sauoq
    "My two cents aren't worth a dime.";
    

      Acutally I didnt use that deliberately, the reason being that what you wrote is pretty well the same as the index solution, even though it doesnt look it. The idea of the s/// was to avoid coming back to the perl runloop, and instead stay inside of the regex loop.

      ---
      $world=~s/war/peace/g