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!

    @LINES = <FILE>; 
    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 (OUTFILE);


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?

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. :)