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

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

This node falls below the community's threshold of quality. You may see it by logging in.

Replies are listed 'Best First'.
Re: Counting the number of replaces
by McDarren (Abbot) on Jun 26, 2006 at 09:42 UTC
    Yes, just evaluate your regexp in scalar context, eg:
    $num_replacements = $_ =~ s/<I>/<italic>/g;

    Cheers,
    Darren :)

Re: Counting the number of replaces
by GrandFather (Saint) on Jun 26, 2006 at 09:46 UTC

    Note too that the $_ =~ is redundant. The regex on its own is quite sufficient: my $count = s/<I>/<italic>/g;.


    DWIM is Perl's answer to Gödel
Re: Counting the number of replaces
by pingo (Hermit) on Jun 26, 2006 at 10:11 UTC
    In the spirit of TIMTOWTDI:
    s/<I>/$count++;"<italic>"/eg; print $count || 0;
    No, I didn't say it was pretty. ;-)
Re: Counting the number of replaces
by cognizant (Pilgrim) on Jun 26, 2006 at 09:38 UTC
    Try this. $a = $b=~s/<i>/<italic>/g; print "$a"; Gives the output you need.
      I know this is only a quick example, but in general i would avoid using the special variables $a and $b


      This is not a Signature...
Re: Counting the number of replaces
by Moron (Curate) on Jun 26, 2006 at 13:49 UTC
    If you want to get the number of replacements made in the whole file, not just for a particular line, then these should accumulate e.g. using += :
    while( <$inputfh> ) { $replcount += s/replacethis/withthis/g; print $outputfh $_; }

    -M

    Free your mind

Re: Counting the number of replaces
by shmem (Chancellor) on Jun 26, 2006 at 09:54 UTC
    rsriram, please read How do I post a question effectively?. Your could have found the answer for your last questions by yourself, skimming through perfunc (perl function reference) and perlop (perl operator reference).

    cheers,
    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Re: Counting the number of replaces
by ForgotPasswordAgain (Priest) on Jun 26, 2006 at 13:19 UTC
    I noticed that I had an incorrect superstition about using <I>, namely the brackets, in the left side of s///, as I thought it was normally replaced by reading from a filehandle. It seems to work here, though, so I wonder why I believed that....
      Because Perl is rather context-sensitive and uses <I> to mean that in other contexts? In the code:
      while (<I>) { s/<I>/<italic>/g; }
      the first <I> reads from a filehandle and the second is literal text to replace. Fun, isn't it? :)