Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re: Word replace - notetab light vs perl

by blazar (Canon)
on Oct 06, 2005 at 09:56 UTC ( #497870=note: print w/replies, xml ) Need Help??

in reply to Word replace - notetab light vs perl

Your post as been already discussed at length, I'd just like to add that (maybe you didn't know and may be glad to know that) instead of
open(FH, "wrongs") or die $!; open(FH2, ">wrongs2") or die $!; while ($line = <FH>) { $line =~ s/wrongs/wrongs3/; print FH2 "$line"; } close (FH); close (FH2);
you can use some cmd line swithces and arguments and shell redirection (this particular one works in any common shell that I know of, including
perl -lpe 's/wrongs/wrongs3/' wrongs >wrongs2
perl -lpi -e 's/wrongs/wrongs3/' wrongs
if you want in place editing. But under Windows AFAIK you will have to do (something like):
perl -lpe "s/wrongs/wrongs3/" wrongs >wrongs2
perl -lpi.bak -e "s/wrongs/wrongs3/" wrongs
respectively instead; i.e. use double quotes for quoting and cannot do in place editing withou backup.
Modified my Perl code to count the number of replacements as well as added benchmarking:
The code above can easily be adapted to show the count:
perl -lpi '$c++ if s/wrongs/wrongs3/; END{warn "count=$c\n"}' wrongs
For the benchmark, it's not just that easy. That's what is for, and indeed it works by repeating the code to be tested a suitable number of times. But if the task takes long enough, then bash's time command will suffice: here's a test on a file that's 3494270 lines long:
$ time perl -lpe '$c++ if s/sex/cool/; END{warn "count=$c\n"}' gse1.lo +g >/dev/null count=2840 real 0m19.062s user 0m16.736s sys 0m0.940s
Unfortunately it's not available under and cmd.exe, that I know.

Last, you may also want to count the number of substitutions when the /g global modifier is given. In that case

perl -lpi '$c+=s/wrongs/wrongs3/g; END{warn "count=$c\n"}' wrongs
or else you may use the "highly experimental" </c>(?{ code })</c> regex feature:
perl -lpi 's/wrongs($c++)/wrongs3/g; END{warn "count=$c\n"}' wrongs
but there's really no need for it here...

Replies are listed 'Best First'.
Re^2: Word replace - notetab light vs perl
by kiat (Vicar) on Oct 06, 2005 at 10:27 UTC
    Thanks, blazar!

    I've never used command line perl so "-lpi" is alien to me. It's about time to familiarise myself with the basic swiches.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://497870]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (10)
As of 2018-11-21 11:54 GMT
Find Nodes?
    Voting Booth?
    My code is most likely broken because:

    Results (239 votes). Check out past polls.