954,523 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Perl problems writing output to file

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;
BioJavaPhobic
Newbie Poster
11 posts since Feb 2011
Reputation Points: 10
Solved Threads: 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?

d5e5
Practically a Posting Shark
810 posts since Sep 2009
Reputation Points: 159
Solved Threads: 159
 

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

roswell1329
Junior Poster in Training
71 posts since May 2006
Reputation Points: 21
Solved Threads: 2
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: