perlmeditation
kiat
Hi monks,<p>
Thought this was interesting...<p>
I've a text file that has about 35 000 lines. Every line contains a word that I wanted to replace. I opened the file in NoteTab Light and conveniently used its Replace function to do the replacement. A total of 35 000 replacements were made. It took a while and that got me curious because I'm running Pentium 4 @ 3.20 GHz with 512 MB RAM.<p>
I decided to time the process and found out that it took about 35 seconds - I had no idea how to time it automatically so I used an online stopwatch.<p>
I was naturally curious how fast it would be done in Perl. Amazingly, Perl took <strike>less than 2 secs</strike> around 1 second. It was hard to believe so I opened the new file to verify the results. Yes, there were indeed 35 000 lines and all the occurences of the word were replaced.<p>
Amazing!<p>
<code>
open(FH, "wrongs") or die $!;
open(FH2, ">wrongs2") or die $!;
while ($line = <FH>) {
$line =~ s/wrongs/wrongs3/;
print FH2 "$line";
}
close (FH);
close (FH2);
</code>
P.S: If I hadn't done it first in NoteTab Light, I wouldn't have any notion how "fast" Perl's 1 sec is.<p>
<b>Update</b><p>
Tried doing it in Notepad (the one that comes with Windows) and it hanged!<p>
<b>Update2</b><p>
Modified my Perl code to count the number of replacements as well as added benchmarking:
<code>
use Benchmark;
$start = new Benchmark;
open(FH, "wrongs") or die $!;
open(FH2, ">wrongs2") or die $!;
while ($line = <FH>) {
$counted = () = $line =~ s/wrongs/wrongs4/;
$counted2++ if $counted;
print FH2 "$line";
}
close (FH);
close (FH2);
$end = new Benchmark;
# calculate difference
$diff = timediff($end, $start);
print "replaced: $counted2 The operation took: " , timestr($diff, 'all');
# output
# replaced: 35000 The operation took: 0 wallclock secs ( 0.23 usr 0.03 sys + 0.00 cusr 0.00 csys = 0.27 CPU)
</code>
Is there a better way to count the total number of replacements?<p>