The first problem is that your $word_1 has a newline at the end. Since this is almost surely not what you want to do, you should chomp both words after you read them in.

As BazB has pointed out above, you're opening and closing the file several times unnecessarily. Also, if your open fails, there's not much clue about what's happening. It's much clearer to check for errors when opening, then close the handle explicitly, then open it for writing (since you'll be re-writing its contents).

Finally, if you're going to read in the whole file and do match-and-substitute, it's a lot easier not to use an array. Just read the whole thing into a scalar, and do a global replace. Put it all together, and it looks like this:

open HANDLE, $file or die "Couldn't open $file: $!\n"; print "Please Enter a word from $file: "; chomp($word_1 = <STDIN>); print "Please Enter a Word to Replace, $word_1, with: "; chomp($word_2 = <STDIN>); # Read the whole thing in. undef $/; $x = <HANDLE>; close HANDLE; # Re-open for writing, clobbering the file. open HANDLE, ">$file"; # Change every instance $x =~ s/$word_1/$word_2/g; # To prevent changing substrings, it would almost # certainly be better to use: # $x =~ s/\b$word_1\b/$word_2/g; # But it's your call.... print HANDLE $x;

At this point, I should probably also chide you for not using strict and warnings, but I'll let you off easy this time. ;-)

HTH


In reply to Re: swaping words by VSarkiss
in thread swaping words by Anonymous Monk

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.