Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I want to do the following:

replace all instances of "foo" with "bar" in the following string.

$string = "foo, this foo is just a foo";

i tried this:

$string =~ s/foo/bar/;

which works on the first instance, but leaves the rest untouched. There is an unknown number of "foo"'s in a string.

what is the best way to accomplish this?

Replies are listed 'Best First'.
Re: multiple matches in a string
by Juerd (Abbot) on Jan 29, 2002 at 02:27 UTC
    Read about /g in perlre. Then, fix your script and try again. If it works, read perlretut and don't stop reading until you reach the end.

    2;0 juerd@ouranos:~$ perl -e'undef christmas' Segmentation fault 2;139 juerd@ouranos:~$

Re: multiple matches in a string
by ferrency (Deacon) on Jan 29, 2002 at 02:30 UTC
    perldoc perlre

    To replace All occurrances of a match in a string, instead of just the first, use the /g flag:

    $string = "foo, this foo is just a foo"; $string =~ s/foo/bar/g;
    Update:"perldoc perlre" was my attempt at a friendly "rtfm" :) Sorry it didn't come across forcefully enough :)

    Alan

    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: multiple matches in a string
by dws (Chancellor) on Jan 29, 2002 at 02:28 UTC
    ... which works on the first instance, but leaves the rest untouched.

    Consult whatever documentation you have on hand (perlre, if you have the on-line docs), and meditate on the meaning of /g