I need to search a file for one of three patterns and replace it with one of three patters.

currently my code snippet looks like this:

while(<INFILE>){ $_ =~ s/$searchPattern1/$repalcePattern1/g; $_ =~ s/$searchPattern2/$replacePattern2/g; $_ =~ s/$searchPattern3/$replacePattern3/g; print OUTFILE $_; } # end while

Is there perhaps a more elegant way to do this? Also I would Like to print to screen conditionally based on the pattern replaced ie:

if ($_ == s/$searchPattern1/){ print("$searchPattern1 replaced with $replacePattern1 \n"); }elsif ($_ == s/$searchPattern2/){ print("$searchPattern2 replaced with $replacePattern2 \n"); }elsif ($_ == s/$searchPattern3/){ print("$searchPattern3 replaced with $replacePattern3 \n"); }else{ print("Search Patterns not found"); }

although at that point I can maybe change it to:

while(<INFILE>){ if ($_ == s/$searchPattern1/){ $_ =~ s/$searchPattern1/$repalcePattern1/g; print("$searchPattern1 replaced with $replacePattern1\n"); }elsif ($_ == s/$searchPattern2/){ $_ =~ s/$searchPattern1/$repalcePattern1/g; print("$searchPattern2 replaced with $replacePattern2\n"); }elsif ($_ == s/$searchPattern3/){ $_ =~ s/$searchPattern1/$repalcePattern1/g; print("$searchPattern3 replaced with $replacePattern3\n"); }else{ print("Search Patterns not found"); } print OUTFILE $_; } # end while
but that doesn't seem to be working... also as an aside is there a way to remove all the spaces at the end of a line and add a new line character? ie:
<SOURCEFILE> foo bar <\n> foobar <\n> BlahBlah Blah <\n> to: foo bar<\n> foobar<\n> BlahBlah Blah<\n>

In reply to Conditional Search and Replace by PyrexKidd

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.