perl@1983 has asked for the wisdom of the Perl Monks concerning the following question:

I am new to Perl. I was wondering whether it is possible to do something like below: $var =~ s/\n//g =~ s/\s+//g; Basically I want to perform one search n replace operation on a variable, another search and replace on the result of previous operation and so on... Above syntax doesn't work. Is there any apparent work around generally being practiced? Thanks in advance.
  • Comment on Multiple Search and Replace in Single Line

Replies are listed 'Best First'.
Re: Multiple Search and Replace in Single Line
by LanX (Saint) on May 02, 2011 at 21:45 UTC
    well if it's absolutely necessary that the second replacement occurs only after the first has finished, you need a loop.

    something like

     $var =~ s/$_//g for qw(\n \s+);

    Cheers Rolf

Re: Multiple Search and Replace in Single Line
by jwkrahn (Abbot) on May 03, 2011 at 02:12 UTC

    The usual way to do that in Perl is:

    s/\n//g, s/\s+//g for $var;

    But that is really redundant as \n is part of the character class \s so just doing:

    $var =~ s/\s+//g

    Would accomplish the same result.

Re: Multiple Search and Replace in Single Line
by wind (Priest) on May 02, 2011 at 21:37 UTC

    If you're wanting to strip more than one thing, just use |

    $var =~ s/\s+|\n//g;

    However, the character class \s contains \n, so it's redundant.