Using eof is the right approach... What was your eof attempt? Looking at your code above, you can't count the lines like that without reseting the file before reading the whole thing again.. I believe that this should work (untested):
open(TXTIN,"ARGV[0]") || die "Cannot open the data file"; open(TXTOUT,">ARGV[1]") || die "Cannot open the formatted file"; while(<TXTIN>){ # gets a line from input file if( eof TXTIN ){ # eof returns true if the _next_ re +ad would fail, meaning s/different/regex here/; # the one we just read was the l +ast line }else{ s/yada/yadda/; } print TXTOUT $_; } close(TXTIN); close(TXTOUT);
Also, i don't think you want to chomp the input and then not write a newline to the output file (so i just omitted the chomp from my snippet)...

Note that (and this one i tested) you can also use the commandline here:
perl -pe 'if( !eof ){ s/^1/AAAA/; } else{ s/^1/BBBB/; }' /etc/hosts > +/tmp/newfile
And if you want to do an in-place edit (see perlrun) you can just add the -i command-line parameter.

one last note: if you're not doing use strict; and use warnings;, they will be invaluable to you to add.. (maybe you just omitted them from your code snippet -- just worth double-checking)

ok, one last note-- it doesn't apply to this specific task, but the $. variable might be of interest to you -- see perlvar (e.g. if you wanted the first line to have a different regex)

In reply to Re: While.For loop noob query by davidrw
in thread While.For loop noob query by jriggs420

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.