Perl is my first programming language. I wrote this to play with pattern matching and filehandles. Please could someone explain why this code does everything I ask except print to the screen a count of the number of instances of the word I'm substituting? Massive thanks.
#! c:\perl\bin print("Enter filename to open (text only):\n\n"); $in=<STDIN>; chomp $in; if ($in !~ /\.txt$/i) { $in.=".txt"; } open ($in, "$in") or die("$in could not be opened:$!\n"); print("Enter string to replace \"and\" with:\n\n"); $word=<STDIN>; chomp $word; print("Enter filename to SAVE text file as:\n\n"); $out=<STDIN>; chomp $out; if ($out !~ /\.txt$/i) { $out.=".txt"; } open($out, ">$out") or die $!; print ("\n\n\n"); $count=0; while (<$in>) { s/\band\b/$word/ig; while (/\band\b/ig) { ++$count; } print($out "$_\n"); } print "there were $count instances of \"and\" in $in"; close $out; close $in;
UPDATE. Thanks everyone! Most helpful.

In reply to Counting instances of words by scarymonster

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.