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

In the code below I want to replace the word Apple with Mango. But something is wrong.please help me.

use strict; use warnings; use diagnostics; my $string = "Apple has determined that, in very rare cases, the batte +ry in the iPod nano (1st generation)may overheat and pose a safety ri +sk. Affected iPod nanos were sold between September 2005 and December + 2006.This issue has been traced to a single battery supplier that pr +oduced batteries with a manufacturing defect.While the possibility of + an incident is rare, the likelihood increases as the battery ages.Ap +ple recommends that you stop using your iPod nano (1st gen) and follo +w the process noted below to order a replacement unit, free of charge +."; $string = s/Apple/Mango/g; print"$string";

Replies are listed 'Best First'.
Re: Search and replace problem
by atcroft (Abbot) on Jan 10, 2012 at 05:22 UTC

    The problem you are having is that you have this: $string = s/Apple/Mango/g; where you actually want this: $string =~ s/Apple/Mango/g;

    The '=~' applies the substitution to $string, whereas the '=' tries to assign the result of the attempted substitution on $_. (May not be exactly what occurs, but pretty close.)

    Hope that helps.

Re: Search and replace problem
by Xiong (Hermit) on Jan 10, 2012 at 10:37 UTC

    I applaud your willingness to post an actual example script and actual example data. Please allow me to offer a number of points:

    • It's often better to specify a minimum version of perl. See also Perl::MinimumVersion.
    • A small amount of sample data is often as good as more.
    • Limit lines to 78 columns. Continuations are okay. If I really did need to hardcode a big paragraph, though, I might read it in from <DATA>. See perldata, Special Literals.
    • Proper indentation and spacing go a long way toward making code readable.
    • Use interpolating quotes only when you want to interpolate.
    • atcroft is correct in that your original script attempts to perform substitution on $_ ("it"); if successful, the expression evaluates to the number of substitutions performed.
    The following script attempts to illustrate each of the points above.
    use 5.010000; use strict; use warnings; use diagnostics; my @foo = (qw| Pear Apple AppleTomatoApple |); for ( @foo ) { my $text = 'Apple has determined, ' . 'the iPod nano ' . 'may overheat. ' ; my $assign = 'Blueberry jam vendor!'; $text =~ s/Apple/Mango/g; # sub's on $text $assign = s/Apple/Mango/g; # sub's on $_ and yields num of su +ccess say '$text: ', $text, "\t", '$assign: ', $assign, "\t", '$_: ', $_ +; };
    I'm not the guy you kill, I'm the guy you buy. —Michael Clayton

      Thanks a lot Xiong. I learned a lot from your reply.

        Glad to help.

        I'm not the guy you kill, I'm the guy you buy. —Michael Clayton