It is inefficient to read the input file twice. It doesn't matter if the file is small, but it is easy enough to do everything in a single pass over the file.

If the data you want to remove is a fixed width at the end of the line, you can use substr - you don't need substitution.

use strict; use warnings; my $line = <DATA>; while(<DATA>) { if(/^sb1 1.0 142r$/) { print substr($line, 0, -13) . "\n"; } else { print $line; } $line = $_; } print $line; __DATA__ lines before the changed section 4.62399E+09 2.90871E+09 7.17338E+14 sb1 1.0 142r lines after the changed section another instance of the lines to be changed 4.62399E+09 2.90871E+09 7.17338E+14 sb1 1.0 142r another line with 7.17338E+14 in it the rest of the file

produces

lines before the changed section 4.62399E+09 2.90871E+09 sb1 1.0 142r lines after the changed section another instance of the lines to be changed 4.62399E+09 2.90871E+09 sb1 1.0 142r another line with 7.17338E+14 in it the rest of the file

Notice that the output still contains 7.17338E+14. Simple grepping the output file for this value is not a good test for whether the file was changed unless you know the value can't appear elsewhere in the file. I would use diff to see if two text files were different.

Notice also that the file may be changed in more than one place. This may not be what you want.

update: if(/^sb1 1.0 142r$/) { is incorrect. There are many alternatives, including if(/^sb1 1\.0 142r$/) { and if($_ eq 'sb1 1.0 142r') {.


In reply to Re: how to read in a line containing exponentials by ig
in thread how to read in a line containing exponentials by pattobw

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.