in reply to write exact lines of file

Here's a method that's inelegant, but instructive and clear:

1. Read the contents of your file into an array:

open(FILE, filename); @LINES = <FILE>; close(FILE);

Each array element now contains one line of the file.

2. Now you can operate as you wish on the desired array elements to insert/change/delete desired new lines. For example, to change the nth line;

$LINES[n] = 'some new text';

or, to take the nth to pth lines of another file and replace the nth to pth lines of your original with them:

open(FILE, filename1); @LINES = <FILE>; close(FILE); open(FILE2, filename2); @LINES2 = <FILE2>; close(FILE2); for $i (n .. p) { $LINES[$i] = $LINES2[$i]; }

3. Re-write from the array to the file:

open(FILE, filename); for $i (0 .. $#LINES) { print FILE "$LINES[$i]"; } close(FILE);

Replies are listed 'Best First'.
Re: Re: write exact lines of file
by helgi (Hermit) on Oct 09, 2003 at 09:52 UTC
    No warnings, no strictures. Bad.

    use warnings; use strict;
    You should always, yes, always, check the results of system calls for errors.

    open(FILE, filename) or die "Cannot open filename:$!\n";

    There is absolutely no need in any of the examples to read the file into an array. It is faster and far less memory wasteful to loop through the file with while:

    while (<FILE>) { # do stuff }

    In your 3rd example, you are not opening the file for writing, so writing will fail. This would have been caught if you had allowed warnings.

    There are more problems, but since many posts above have dealt with this problem much better, I will cease now.


    --
    Regards,
    Helgi Briem
    hbriem AT simnet DOT is