daseme has asked for the wisdom of the Perl Monks concerning the following question:

i am using Aristotles code from Extracting HTML between comments which is working great. i can extract the data i want and print it to screen. i can also append the extracted data to the original file. However i want to rewrite the original file with the extracted data. When i open the file to write it empties the original file. below is the append which works. what can i do?
#!/usr/bin/perl -w # turn on perl's safety features use strict; use diagnostics; use HTML::TokeParser::Simple; #define variable my $dirname="./"; my @files=undef; my $file=undef; my $newcontent=undef; opendir(DIR, $dirname) or die "can't opendir $dirname: $!"; @files = readdir(DIR); closedir(DIR); foreach $file (@files) { if($file =~ /\.html$/ && -T $file) { # do something with "$dirname/$file" my $stream = HTML::TokeParser::Simple->new($file) || die "Couldn't + read file $file: $!"; print "\n\nProcessing $file\n\n"; open FH, ">", $file or die "Error writing '$file': $!\n"; while ( my $token = $stream->get_token ) { if (( $token->is_comment and $token->as_is eq '<!--Sta +rt FULL TEXT-->') .. ($token->is_comment and $token->as_is eq '<!--End FULL TEX +T-->')){ $newcontent = $token->as_is; #if $token->is_text; print $newcontent; print FH $newcontent; } } close FH; } } exit(0);

Replies are listed 'Best First'.
Re: print inside while using HTML::TokeParser::Simple;
by friedo (Prior) on Apr 28, 2005 at 21:51 UTC
    Change the open statement from append mode ( >>) to overwrite mode ( >). See open for more.
      thks for the quick response. my problem is when i use overwrite mode the file is emptied by the script. i have updated the script above to show in overwrite mode.
        I don't understand your question, then. You said you want to rewrite the file with new data, and you don't want to append. Now you're saying you don't want the file overwritten. What exactly are you trying to accomplish?