0

I want to remove all lines in a text file that start with HPL_ I have acheived this and can print to screen, but when I try to write to a file, I just get the last line of the amended text printed in the new file. Any help please, thank you!

open(FILE,"<myfile.txt"); 
    @LINES = <FILE>; 
    close(FILE); 
    open(FILE,">myfile.txt"); 
    foreach $LINE (@LINES) { 
    @array = split(/\:/,$LINE); 


    my $file = "changed";

    open OUTFILE, ">$file" or die "unable to open $file $!";

    print OUTFILE $LINE unless ($array[0] eq "HPL_");

    } 
    close(FILE); 
    close (OUTFILE);




    exit;
3
Contributors
2
Replies
4
Views
6 Years
Discussion Span
Last Post by roswell1329
0

Remove the following line from inside your foreach loop and put it before the beginning of the loop starts. open OUTFILE, ">$file" or die "unable to open $file $!"; Opening a file for output multiple times results in overwriting the existing file each time so that only the last thing written will remain in the final version of the file.

Also in line 4, after you close your input file you re-open it for output and then don't print anything to it. Why?

0

If you're in *NIX you can do this same thing with one line:

$ perl -ni.bak -e 'print unless $_ !~ /^HPL_/;' datafile

This will create a backup of your data file (called "datafile.bak") and will modify the original by stripping out all lines that do not begin with "HPL_". No script file is required. :)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.