http://www.perlmonks.org?node_id=81922


in reply to Replacing a given character starting with the xth occurence in a string

Um, I'm pretty new to perl, but your problem is very simple really. I think everyone has tried to make it much more complicated a problem than it really is.

Try this:

#!/usr/perl -w my p$ = 'Terrence and Phillip are sweet'; p$ =~ s/w/1/g;
p$ will then contain "T1rr1nc1 and Phillip ar1 sw11t", I think you'll find.

sharle

  • Comment on Re: Replacing a given character starting with the xth occurence in a string
  • Download Code

Replies are listed 'Best First'.
Re: Re: Replacing a given character starting with the xth occurence in a string
by quent (Beadle) on May 21, 2001 at 10:25 UTC

    You wouldn't be the first person here to misread (and therefore mis-answer) a question, so we might all want to be lenient on that account (but do go back and read the original question again, it isn't quite a simple substitution question). But everyone should take the time to test the code that they post at least minimally. Your code does not compile because the variable should be $p not p$, and making that change doesn't give the result you stated because your code replaces w's instead of e's. It looks as if you are trying to be careful by using -w and my() variables, so maybe you tested code and then retyped it for submission, making typos as you went. Copy and paste is a much safer way to participate in online forums.

      You're right of course, my code should have been:

      #!/usr/bin/perl -w my $p = 'Terrence and Philip are sweet'; $p =~ s/e/1/g; print "$p";

      which is a direct copy and paste, but still doesn't give the desired result, I see after re-reading. I'll have to think about that a little harder. Now I see why it wasn't as easy as I thought at first go.

      sharle

        Also worth noting that for single character translations like this, tr/// is much more efficient than s///.

        --
        <http://www.dave.org.uk>

        "Perl makes the fun jobs fun
        and the boring jobs bearable" - me