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

An optimization question for the monks:

I have 2 search and replace lines in a script:

s/"//g;

s/\s\s/\;/g;

It operates on a text file and does what it should; how can I combine these two lines into one nice operation (ie, strips out quotes AND replaces 2 spaces with a semicolon)??

Thanks,

Glenn

Replies are listed 'Best First'.
(jeffa) Re: compound search and replace
by jeffa (Bishop) on Jun 20, 2002 at 19:44 UTC
    Do you want spaces or whitespace? You use \s, but you say replace 2 spaces. Here is how you could replace two spaces (not tabs or newlines) and all double quotes:
    use strict; my %replace = ( '"' => '', ' ' => ';', ); s/("| )/$replace{$1}/g;

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: compound search and replace
by RMGir (Prior) on Jun 20, 2002 at 19:40 UTC
    You COULD do it. Whether you SHOULD do it is a different question...
    s/("|\s\s)/($1 eq '"')?'':';'/eg;
    I bet if you benchmarked that, it would be slower than the 2 separate searches, both because of the more complex search part, and the "/e" expression based replace.
    --
    Mike
Re: compound search and replace
by grinder (Bishop) on Jun 20, 2002 at 20:11 UTC

    I would just note in passing that whenever you are dealing with single characters, you should use the tr (transliterate) operator rather than the more heavy-duty s/// operator.

    To strip out those double quotes, you should say tr/"//d instead.

    print@_{sort keys %_},$/if%_=split//,'= & *a?b:e\f/h^h!j+n,o@o;r$s-t%t#u'

Re: compound search and replace
by I0 (Priest) on Jun 20, 2002 at 21:20 UTC
Re: compound search and replace
by ides (Deacon) on Jun 20, 2002 at 19:58 UTC
    You'll also want to try using /og instead of just /g as this will only compile the regex once, and not once per line of your text file.

    -----------------------------------
    Frank Wiles <frank@wiles.org>
    http://frank.wiles.org