open INFILE, "<" . $filename or die "Couldn't open file " . $filename . " for reading : $!"; open OUTFILE, ">" . $filename or die "Couldn't open file " . $filename . " for writing : $!"; while (<INFILE>){ print OUTFILE $_; last if /$heading_to_print/; } while (<INFILE>){ print OUTFILE $_ unless /$heading_to_print/; } close INFILE; close OUTFILE;
A little tip is in your error messages for open() and similar you shuld include the output of $!. Also personally I dont like using global filehandles. I prefer to use lexical ones, but this only works on later versions of Perl.

HTH

UPDATE

This will remove any duplicate lines except the first, not just that of a specific line. (Although it might chew up a lot of memory if there are only a few dupes but many lines.)

open INFILE, "<" . $filename or die "Couldn't open file " . $filename . " for reading : $!"; open OUTFILE, ">" . $filename or die "Couldn't open file " . $filename . " for writing : $!"; my %hash; while (<INFILE>){ print OUTFILE $_ unless $hash{$_}++; } close INFILE; close OUTFILE;
This could also be done as a one liner,
perl -ni.old -e "print $_ unless $_{$_}++" foo.txt
Which really is quite nice isnt it. :-) (Note that the file will be "edited-in-place", and the original will be backed up as "foo.txt.old")

Yves / DeMerphq
---
Writing a good benchmark isnt as easy as it might look.


In reply to Re: Replacing all but one duplicate lines by demerphq
in thread Replacing all but one duplicate lines by johnirl

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.