http://www.perlmonks.org?node_id=1027156


in reply to removing lines that are in the end of a file

truncate combined with tell seems to be pretty straight-forward:

open my $fh, '+<', 'test.txt' or die $!; my $last_matched = 0; my $told = 0; while( my $line = <$fh> ) { my $matched = $line =~ m/SIL$/; truncate $fh, $told and last if $matched && $last_matched; $last_matched = $matched; $told = tell $fh; } close $fh or die $!;

Dave

Replies are listed 'Best First'.
Re^2: removing lines that are in the end of a file
by BrowserUk (Patriarch) on Apr 05, 2013 at 15:46 UTC

    Your solution would truncate the OPs sample data before the first line. (Which also contains "SIL").

    Ie. It would empty the file.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

      No, it would truncate after the first line that ends in SIL that is followed by a line ending in SIL; that much I did test. It works as it should for the data the OP posted, but your read-backwards solution is better because it doesn't make the assumption that SIL lines are only repeated in succession at the end of the file in the real data-set. Had I seen yours before posting I wouldn't have bothered since it's a more reliable variation on the tell and truncate theme. ;)


      Dave

        Actually, mine's wrong also. Looking back he wants to retain the first of the last set of SIL lines :(

        It should be a simple adjustment though.


        With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority".
        In the absence of evidence, opinion is indistinguishable from prejudice.