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 :) | [reply] [d/l] |
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
| [reply] [d/l] [select] |
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. ;-) | [reply] [d/l] |
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. | [reply] [d/l] [select] |
|
| [reply] |
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 $_;
}
| [reply] [d/l] |
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}
| [reply] |
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.... | [reply] [d/l] [select] |
|
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? :) | [reply] [d/l] [select] |