Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re^2: Replacing a specfied instance of a pattern in a string

by Roy Johnson (Monsignor)
on Jul 14, 2005 at 22:01 UTC ( [id://475065]=note: print w/replies, xml ) Need Help??


in reply to Re: Replacing a specfied instance of a pattern in a string
in thread Replacing a specfied instance of a pattern in a string

A tad simpler looping, and case-insensitive:
my $foo = 'Fsih my test variable is fsihd or is it gfsih or gfsihd f +sih'; my $from = 'fsih'; my $which = 3; my $to = 'FISH'; # makes it easy to see $foo =~ /\Q$from\E/ig for (1..$which); substr($foo, pos($foo) - length($from), length($from), $to) if pos($fo +o); print "Foo = $foo\n";

Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^3: Replacing a specfied instance of a pattern in a string
by ikegami (Patriarch) on Jul 14, 2005 at 22:48 UTC
    That reminds me of /c!
    my $str = 'Fsih my test variable is fsihd or is it gfsih or gfsih +d fsih'; # 1111 2222 3333 + 4444 my $substr = 'fsih'; my $regexp = qr/\Q$substr\E/; my $replace = 'fish'; my $instance = 3; # 3rd print("$str\n"); scalar $str =~ /\G.*?$regexp/gc while --$instance; $str =~ s/\G(.*?)$regexp/$1$replace/; print("$str\n");

    The /c is needed in case there are less than $instance instances of the search string.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://475065]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (None)
    As of 2024-04-25 01:43 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      No recent polls found