in reply to regular expression

shevek: It re-opens the same file for output.

toniax: You say you are new to Perl programming, and by implication you may be new to programming in general. If so, it is well to point out a critical side-effect of your OPed program: When the file is re-opened for output, the original content of the file is destroyed. The only place the original file content still exists is in an array in your program. If your program should fail for any reason before the original content is completely processed, the output file will be left only partly full of processed data – and possibly entirely empty.

One approach to handling a situation like this (in which processed output data is intended to be held in a file with the same name as the input file) would be:

  1. Open a temporary file (e.g., date.txt.out) and write processed data to this file. When processing is complete and the temp file is closed without error,
  2. the original input file is renamed (e.g., to date.txt.bak). If the input file rename operation is error-free,
  3. the output file is renamed to its final form (e.g., date.txt), and if this operation is successful,
  4. perhaps delete the temporarily renamed input file (although this file may instead be left behind as a .bak file).

Note that error checking is vital at each stage of this process. In this way, much grief may be avoided.

Replies are listed 'Best First'.
Re^2: regular expression
by toniax (Scribe) on Oct 31, 2010 at 21:51 UTC
    Yes I am new to programing in the sense that , I want to learn how it works. I can take snippets of code and put it together and make a program . I will work but be a program that is full of flaws such as you point out to me . You made some great points and I will use your advice and change my program for the better of data preservation. So much more for me to learn. I really do appreciate all the help everyone is giving me . Thanks again
Re^2: regular expression
by toniax (Scribe) on Nov 02, 2010 at 00:09 UTC
    Hello I changed my program . And added the features you suggested. I know a better way must exist . Can any one help.
    $openx = open(BAKFIL, "<data.txt"); open(BAKFIL2, ">data.bak.txt"); if ( ! $openx ) { print "Content-type:text/html\n\n"; print "File Does not exist. Program will now abort"; close( BAKFIL ); close( BAKFIL2 ); unlink( "data.bak.txt"); exit ; } else { while(<BAKFIL>) { print BAKFIL2 $_; } close( BAKFIL ); close( BAKFIL2 ); } my $filesize = -s "data.txt"; open(XFIL,"data.txt") || die $!; @main = <XFIL>; close(XFIL); open(XFIL,">data.txt") || die $!; foreach $main_line (@main) { print XFIL $main_line; if ($main_line =~ /The marker line/) { print XFIL "Hello\n"; } } close(XFIL); my $filesizemain = -s "data.txt"; if ($filesizemain < $filesize) { open(BAKFIL2, "<data.bak.txt") || die $!; open(BAKFIL, ">data1313.txt") || die $!; while(<BAKFIL2>) { print BAKFIL $_; } close( BAKFIL2 ); close( BAKFIL );